Math取整

Math类中的三个与取整有关的方法
1、public static double ceil(double a)

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. Special cases:
If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
If the argument value is less than zero but greater than -1.0, then the result is negative zero.
Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x).

Parameters:
a - a value.
Returns:
the smallest (closest to negative infinity) floating-point value that is greater than or equal to the argument and is equal to a mathematical integer.

向上取整,Math.ceil(12.2)的结果为13,Math.ceil(-12.7)的结果为-12

2、public static double floor(double a)

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. Special cases:
If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

Parameters:
a - a value.

Returns:
the largest (closest to positive infinity) floating-point value that less than or equal to the argument and is equal to a mathematical integer.
向下取整,Math.floor(12.7)的结果是12,Math.floor(-12.4)的结果-13

3、public static int round(float a)

Returns the closest int to the argument, with ties rounding up.
Special cases:
If the argument is NaN, the result is 0.
If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Parameters:
a - a floating-point value to be rounded to an integer.

Returns:
the value of the argument rounded to the nearest int value.
See Also:
Integer.MAX_VALUE, Integer.MIN_VALUE
表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果12,Math.round(-11.5)的结果为-11

你可能感兴趣的:(Math取整)