Math类中提供了三个与取整有关的方法:ceil(),floor(),round()
首先看一下Math类的部分源码
我们可以知道,ceil()和floor()返回的都是double类型;round()返回的是int 和 long 类型。
这些方法的作用于它们的英文名称的含义相对应
1、ceil()
ceil的英文意义是天花板,该方法就表示向上取整,Math.ceil(11.2)的结果为12.0,Math.ceil(-11.2)的结果为-11.0;
@Test
public void ceil(){
System.out.println(Math.ceil(11.2)); //12.0
System.out.println(Math.ceil(-11.2)); //-11.0
}
2、floor()
floor的英文是地板,该方法就表示向下取整,Math.floor(11.2)的结果是11.0,Math.floor(-11.2)的结果-12.0;
@Test
public void floor(){
System.out.println(Math.floor(11.2)); //11.0
System.out.println(Math.floor(-11.2)); //-12.0
}
3、ceil()
最难掌握的是round方法,他表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.2)的结果是11,Math.round(-11.2)的结果为-11,Math.round(-11.6)的结果为-12,
@Test
public void round(){
System.out.println(Math.round(11.2)); //11
System.out.println(Math.round(-11.2)); //-11
System.out.println(Math.round(-11.6)); //-12
}