一、定义
1 | ceil() “天花板”,向上取最接近的整数。 返回大于等于( >= )给定参数的的最小整数,类型为双精度浮点型。 |
2 | floor() “地板”,向下取最接近的整数。 返回小于等于(<=)给定参数的最大整数 。 |
3 | rint() 返回与参数最接近的整数。返回类型为double。注:如果上下都接近,取偶数。 |
4 | round() 它表示四舍五入,算法为 Math.floor(x+0.5),即将原来的数字加上 0.5 后再向下取整,所以,Math.round(11.5) 的结果为12,Math.round(-11.5) 的结果为-11。 |
二、代码示例
public static void main(String[] args) {
double[] nums = {1.4, 1.5, 1.6, -1.4, -1.5, -1.6};
for(double num:nums){
test(num);
}
}
private static void test(double num) {
System.out.println("Math.floor("+num+")="+Math.floor(num));
System.out.println("Math.round("+num+")="+Math.round(num));
System.out.println("Math.ceil("+num+")="+Math.ceil(num));
System.out.println("Math.rint("+num+")="+Math.rint(num));
}
Math.floor(1.4)=1.0
Math.floor(1.5)=1.0
Math.floor(1.6)=1.0
Math.floor(-1.4)=-2.0
Math.floor(-1.5)=-2.0
Math.floor(-1.6)=-2.0
Math.round(1.4)=1
Math.round(1.5)=2
Math.round(1.6)=2
Math.round(-1.4)=-1
Math.round(-1.5)=-1
Math.round(-1.6)=-2(!!)
Math.ceil(1.4)=2.0
Math.ceil(1.5)=2.0
Math.ceil(1.6)=2.0
Math.ceil(-1.4)=-1.0
Math.ceil(-1.5)=-1.0
Math.ceil(-1.6)=-1.0
Math.rint(1.4)=1.0
Math.rint(1.5)=2.0(!!)
Math.rint(1.6)=2.0
Math.rint(-1.4)=-1.0
Math.rint(-1.5)=-2.0(!!)
Math.rint(-1.6)=-2.0