Why does Math.floor return a double?
JavaMathTypesJava Problem Overview
Official Javadoc says that Math.floor()
returns a double
that is "equal to a mathematical integer", but then why shouldn't it return an int
?
Java Solutions
Solution 1 - Java
According to the same Javadoc:
If the argument is NaN
or an infinity or positive zero or negative zero, then the result is the same as the argument. Can't do that with an int
.
The largest double
value is also larger than the largest int
, so it would have to be a long
.
Solution 2 - Java
It's for precision. The double data-type has a 53 bit mantissa. Among other things that means that a double can represent all whole up to 2^53 without precision loss.
If you store such a large number in an integer you will get an overflow. Integers only have 32 bits.
Returning the integer as a double is the right thing to do here because it offers a much wider usefull number-range than a integer could.
Solution 3 - Java
Others have told you the why, I'm going to tell you how to round correctly given you want to do this. If you are only going to use positive numbers, then you can use this statement:
int a=(int) 1.5;
However, the (int) always rounds towards 0. Thus, if you want to do a negative number:
int a=(int) -1.5; //Equal to -1
In my case, I didn't want to do this. I used the following code to do the rounding, and it seems to handle all of the edge cases well:
private static long floor(double a)
{
return (int) Math.floor(a);
}
Solution 4 - Java
What would you want it to return if you gave it a double bigger than the largest int or long?
(Admittedly if it's bigger than the largest long the precision will be low anyway - it may not be the nearest theoretical integer - but even so...)
Solution 5 - Java
Just as there is an integer and a floating point division in Java, there are integer and floating point ways to do floor:
double f = Math.floor(x);
or
int k = (int) x;
but you always need to be careful with using floor with finite precision arithmetic: your calculation of x may yield something like 1.99999999 which will be floored to 1, not 2 by both forms. There are many algorithms out there that need to work around this limitation to avoid producing wrong results for some input values.
Solution 6 - Java
So that error and other non integer values can correctly cascade through a series of calculations.
For instance, if you feed Not a Number (NaN) into Math.floor, it'll pass it along.
If it returned integer it couldn't pass these status or errors along, and you could get bad results from an earlier calculation that look good but are wrong after further processing.