Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Math.ceil return a double?

When I call Math.ceil(5.2) the return is the double 6.0. My natural inclination 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 a double rather than a long when the result is an integer? I think understanding the reason behind it might help me understand Java a bit better. It also might help me figure out if I'll get myself into trouble by casting to a long, e.g. is

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

always what I think it should be? I fear there could be some boundary cases that are problematic.

like image 536
PengOne Avatar asked Sep 02 '11 17:09

PengOne


People also ask

Is Math ceil double?

ceil() accepts double value as an argument and returns the smallest integer which is greater than or equal to the argument. The returned value is of type double. Following is the syntax of ceil() method.

What is the return type of Math ceil?

The ceil() method rounds the specified double value upward and returns it. The rounded value will be equal to the mathematical integer. That is, the value 3.24 will be rounded to 4.0 which is equal to integer 4.

What does the ceil function return?

The ceil function returns the smallest integer that is greater than or equal to x.

Does Math ceil return an integer?

The Math. ceil() function always rounds a number up to the next largest integer. Note: Math. ceil([ null ](/en-US/docs/Web/JavaScript/Reference/Operators/null)) returns integer 0 and does not give a NaN error.


2 Answers

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.

like image 195
Jon Skeet Avatar answered Oct 14 '22 09:10

Jon Skeet


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.

like image 39
Peter Lawrey Avatar answered Oct 14 '22 11:10

Peter Lawrey