Cast to int vs Math.floor
Asked Answered
C

2

10

Is it save to use cast to int instead of Math.floor to convert float / double values to integers?

var scale = 1.5;
int foo1 = (int)scale;
int foo2 = Math.floor(scale);
Cory answered 11/2, 2019 at 10:58 Comment(0)
S
13

In this case both Case to Int and Math.floor will return integer value. If x=3.5 then both function will return 3 in output. Cast to int is a function to convert variable of any datatype to integer type, on the other hand Math.floor function will only floor the decimal number to integer not converting datatype. But result will be different in case of negative values because Cast to Int approaches to zero and Math.floor approaches to negative infinity. So in that perspective if you are working on real numbers (both positive and negative) then it is unsafe to use Cast to Int instead of Math.floor to get precise output.

Sacristan answered 11/2, 2019 at 11:7 Comment(0)
A
0

As Vala code is translated into C, this is the same question as Cast to int vs floor

TL;DR: yes it is safe but the result of Math.floor and float/double casting are different when negative numbers are given.

Note that Math.floor is part of the GLib library and thus is not available in the POSIX profile.

Antisepticize answered 11/2, 2019 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.