Are there any reasons one would prefer to use Math.Floor vs casting to an integral type?
double num; double floor = Math.Floor(num);
OR
double num; long floor = (long)num;
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.
The Java Math floor() is a mathematical function available in Java Math Library. This function returns the closest integer value (represented as a double value) which is less than or equal to the given double value.
Floor() is a Math class method. This method is used to find the largest integer, which is less than or equal to the passed argument.
Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.
There are some differences between casting to an integral type and using Math.Floor:
It differs for negative values:
double num = -1.3; double floor = Math.Floor(num); // = -2 long cast = (long)num; // = -1
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