Java中取整方法小结
Math类包括五个取整方法:
方法 | 描述 |
---|---|
ceil(x) | x向上取整为它最接近的整数。该整数作为一个双精度值返回。 |
floor(x) | x向下取整为它最接近的整数。该整数作为一个双精度值返回。 |
rint(x) | x取整为它最接近的整数。如果x与两个整数的距离相等,偶数的整数作为一个双精度值返回。 |
round(x) | 如果x是单精度数,返回(int)Math.floor(x+0.5);如果x是双精度数,返回(long)Math.floor(x+0.5)。 |
ceil,floor,round,这些方法的作用于它们的英文名称的含义相对应,例如:
- ceil的英文意义是天花板,该方法就表示向上取整,Math.ceil(11.3)的结果为12,Math.ceil(-11.6)的结果为-11
- floor的英文是地板,该方法就表示向下取整,Math.floor(11.6)的结果是11,Math.floor(-11.4)的结果-12
- rint方法取整为它最接近的整数。如果该值与两个整数的距离相等,偶数的整数作为一个双精度值返回,Math.rint(2.5)的结果是2,Math.rint(-2.5)的结果是-2,Math.rint(4.5)的结果是4
- 最难掌握的是round方法,他表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果是12,Math.round(-11.5)的结果为-11.Math.round( )符合这样的规律:小数点后大于5全部加,等于5正数加,小于5全不加
测试代码如下:
package com.test4;
/**
*
* @author Echo
*
*/
public class Test {
public static void main(String[] args) {
System.out.println(Math.ceil(2.1));//3.0
System.out.println(Math.ceil(2.0));//2.0
System.out.println(Math.ceil(-2.0));//-2.0
System.out.println(Math.ceil(-2.1));//-2.0
System.out.println(Math.floor(2.1));//2.0
System.out.println(Math.floor(2.0));//2.0
System.out.println(Math.floor(-2.0));//-2.0
System.out.println(Math.floor(-2.1));//-3.0
System.out.println(Math.rint(2.1));//2.0
System.out.println(Math.rint(-2.0));//-2.0
System.out.println(Math.rint(-2.1));//-2.0
System.out.println(Math.rint(2.5));//2.0
System.out.println(Math.rint(4.5));//4.0
System.out.println(Math.rint(-2.5));//-2.0
System.out.println(Math.round(2.5));//3
System.out.println(Math.round(2.5f));//3
System.out.println(Math.round(-2.5));//-2
}
}