Why does Math.ceil return a double?
Solution 1:
The range of double
is greater than that of long
. For example:
double x = Long.MAX_VALUE;
x = x * 1000;
x = Math.ceil(x);
What would you expect the last line to do if Math.ceil
returned long
?
Note that at very large values (positive or negative) the numbers end up being distributed very sparsely - so the next integer greater than integer x
won't be x + 1
if you see what I mean.
Solution 2:
A double can be larger than Long.MAX_VALUE
. If you call Math.ceil()
on such a value you would expect to return the same value. However if it returned a long, the value would be incorrect.