Why does Math.ceil return double?

When I call Math.ceil(5.2) , double 6.0 returns. My natural tendency was to think that Math.ceil(double a) would return a long . From the documentation:

ceil(double a)

Returns the smallest (closest to negative infinity) double value that is not less than the argument and is equal to a mathematical integer.

But why return double instead of long when the result is an integer? I think that understanding the reason for this can help me understand Java a little better. It can also help me figure out if I get into trouble by adding to long , for example. this is

long b = (long)Math.ceil(a);

always, what do I think it should be? I am afraid that there may be some boundary cases that are problematic.

+62
java double long-integer ceil
Sep 02 '11 at 17:26
source share
2 answers

The double range is greater than long . For example:

 double x = Long.MAX_VALUE; x = x * 1000; x = Math.ceil(x); 

What would you expect from the last line if Math.ceil returned long ?

Note that with very large values ​​(positive or negative), numbers are ultimately allocated very rarely - so the next integer greater than the integer x will not be x + 1 if you see what I mean.

+58
Sep 02 '11 at 17:28
source share

A double can be greater than Long.MAX_VALUE . If you call Math.ceil() on such a value, you expect to return the same value. However, if it returns long, the value will be incorrect.

+12
Sep 02 '11 at 17:28
source share



All Articles