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);
The main difference between the int() and floor() function is that int() function truncates the number and floor() function rounds down. The difference between int() and floor() functions will be clear when using negative numbers.
Description. This function returns a floating-point value representing the nearest whole number that is less than or equal to the value passed to it. If that value is an integer it will, by definition, be the value math. floor() returns, albeit as float not an integer.
Putting it differently, the floor() is always going to be lower or equal to the original. int() is going to be closer to zero or equal.
In Microsoft Excel the floor function is implemented as INT (which rounds down rather than toward zero). The command FLOOR in earlier versions would round toward zero, effectively the opposite of what "int" and "floor" do in other languages.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With