Why does Math.floor return a double?

官方javadoc说Math.floor返回一个“等于一个数学整数”的double,但为什么它不应该返回一个int?


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.


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.


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);
}
链接地址: http://www.djcxy.com/p/86626.html

上一篇: 设计一个能够告诉数字是否为素数的类

下一篇: 为什么Math.floor返回一个double?