java 中取整操作提供了四种方法:分别是:
public
static
double
ceil(
double
a)
//向上取整
|
|
第一种:ceil是天花板的意思,表示向上取整。 测试:
System.out.println(Math.ceil(
1.01
));
System.out.println(Math.ceil(-
1.01
));
System.out.println(Math.ceil(
1.5
));
System.out.println(Math.ceil(-
1.5
));
|
|
输出结果:
2.0
-
1.0
2.0
-
1.0
|
|
第二种:floor是地板的意思,表示向下取整。 测试:
System.out.println(Math.floor(
1.01
));
|
|
输出:
1.0
|
|
第三种:round执行的就是数学上的四舍五入运行。 查看它源码可知其与floor方法的关系:
|
|
测试:
|
|
第四种:最有意思的,返回最接近参数的整数,如果有2个数同样接近,则返回偶数的那个。它有两个特殊的情况:
1)如果参数本身是整数,则返回本身。
2)如果不是数字或无穷大或正负0,则结果为其本身。
Returns the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close, the result is the integer value that is even. 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 double value.
Returns: the closest floating-point value to a that is equal to a mathematical integer.
测试:
|
|