Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast to int vs Math.floor

Tags:

vala

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);
like image 915
Peter Uithoven Avatar asked Feb 11 '19 10:02

Peter Uithoven


People also ask

Is casting to int the same as floor?

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.

Does Math floor return an int?

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.

What is the difference between integer and floor data type?

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.

Does int round or floor?

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.


1 Answers

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.

like image 185
Shah Muhammad Talha Tahir Avatar answered Sep 27 '22 21:09

Shah Muhammad Talha Tahir