1.代码如下,
public class TestMathRound {
public static void main(String[] args) {
System.out.println("小数点后第一位=5");
System.out.println("正数:Math.round(11.5)=" + Math.round(11.5));//12
System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5));//-11
System.out.println();
System.out.println("小数点后第一位<5");
System.out.println("正数:Math.round(11.46)=" + Math.round(11.46));//11
System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46));//-11
System.out.println();
System.out.println("小数点后第一位>5");
System.out.println("正数:Math.round(11.68)=" + Math.round(11.68));//12
System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68));//-12
}
}
2.结果如下,可以自己运行。
3.本来以为是四舍五入,取最靠近的整数,查了网上说有四舍六入五成双,最后还不如看源码。源码如下,
public static long round(double a) {
if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5
return (long)floor(a + 0.5d);
else
return 0;
}
我们看到round函数会默认加0.5,之后调用floor函数,然后返回。floor函数可以理解为向下取整。
4.综上,Math.round函数是默认加上0.5之后,向下取整。