Math类有很多方法,其中Math.round()、Math.ceil()、Math.floor() 三个方法最是常用,且刚接触的人经常会混淆,在学习过程中,总结如下:
Math.round():四舍五入取值
返回结果类型:根据参数决定
Math.ceil():取比自己大的最小整数
Math.floor():取比自己小的最大整数
举例:
(1)、正数例子
①正数运算例一:
@Test
public void test(){
double a = 1.2;
long round = Math.round(a);//四舍五入取值
double ceil = Math.ceil(a);//比自己大的最小整数
double floor = Math.floor(a);//比自己小的最大整数
System.out.println("round: "+round);
System.out.println("ceil: "+ceil);
System.out.println("floor: "+floor);
}
结果
round: 1
ceil: 2.0
floor: 1.0
②正数运算例二:
@Test
public void test(){
double a = 1.7;
long round = Math.round(a);//四舍五入取值
double ceil = Math.ceil(a);//比自己大的最小整数
double floor = Math.floor(a);//比自己小的最大整数
System.out.println("round: "+round);
System.out.println("ceil: "+ceil);
System.out.println("floor: "+floor);
}
结果:
round: 2
ceil: 2.0
floor: 1.0
(2)、负数例子
① 负数运算例一:
@Test
public void test(){
double a = -1.2;
long round = Math.round(a);//四舍五入取值
double ceil = Math.ceil(a);//比自己大的最小整数
double floor = Math.floor(a);//比自己小的最大整数
System.out.println("round: "+round);
System.out.println("ceil: "+ceil);
System.out.println("floor: "+floor);
}
结果
round: -1
ceil: -1.0
floor: -2.0
②负数运算例二:
@Test
public void test(){
double a = -1.7;
long round = Math.round(a);//四舍五入取值
double ceil = Math.ceil(a);//比自己大的最小整数
double floor = Math.floor(a);//比自己小的最大整数
System.out.println("round: "+round);
System.out.println("ceil: "+ceil);
System.out.println("floor: "+floor);
}
结果
round: -2
ceil: -1.0
floor: -2.0