vala

Cast to int vs Math.floor


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);

Solution

  • In this case, both Cast to Int and Math.floor will return integer values. If x=3.5 then both functions will return 3 as output. Cast to int is a function to convert a variable of any datatype to integer type, on the other hand the Math.floor functions will only floor the decimal number to integer, not converting the datatype. But the result will be different in case of negative values, because Cast to Int rounds towards zero and Math.floor rounds towards negative infinity. So from 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.