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之後,向下取整。