Math.round()
java.lang.Math类有两个round()方法,定义如下:
public static int round(float);
public static long round(double);
它们都返回整数,且采用四舍五入进行运算,运算规则如下:
(1).如果参数为正数,小数点后采用四四舍五入,如果小数点后面>=0.5则整数部分加1,否则舍弃小数点后面的数据。
(2).如果参数是负数,如果小数点后面的<-0.5,则负数整数部分加上-1.否则舍弃小数点后面的数据。
测试代码:
输出:
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
java.lang.Math类有两个round()方法,定义如下:
public static int round(float);
public static long round(double);
它们都返回整数,且采用四舍五入进行运算,运算规则如下:
(1).如果参数为正数,小数点后采用四四舍五入,如果小数点后面>=0.5则整数部分加1,否则舍弃小数点后面的数据。
(2).如果参数是负数,如果小数点后面的<-0.5,则负数整数部分加上-1.否则舍弃小数点后面的数据。
测试代码:
public class Main {
public static void main(String[] args) {
System.out.println("Math.round(1.4):"+Math.round(1.4));
System.out.println("Math.round(1.5):"+Math.round(1.5));
System.out.println("Math.round(1.6):"+Math.round(1.6));
System.out.println("Math.round(-1.4):"+Math.round(-1.4));
System.out.println("Math.round(-1.5):"+Math.round(-1.5));
System.out.println("Math.round(-1.6):"+Math.round(-1.6));
}
}
输出:
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