先简单理解成四舍五入
math.round(4.5) = 5;
math.round(5.3) = 5;
math.round(0.1) = 0;
这很好理解,对吧,小学生都很容易掌握的四舍五入。但是当round()中的值为负数的时候就容易犯错了
先看
math.round(-10.6) = -11
math.round(-10.5) = -10 而不是-11 不应该四舍五吗
注意,这里是负数。round()方法你可以这样理解:就是括号内的数+0.5之后,向下取值,-10.6+0.5=-10.1 向下取值就是-11.同理-10.5+0.5=-10.向下取值就是-10.
当然你也可以用初中常用的数轴来区别: -11<= (-10.6+0.5) <=-10,固应该取值-11. -10 <= (-10.5+0.5) <=-9 固取值-10.这跟正数是一样的 5<= (4.5+0.5) <= 6 取值5
5<= (5.3+0.5) <= 6 取值5一样。
看看源代码
public static long round(double a) {
return (long)floor(a + 0.5d);
}
其原理就是这样。四舍五入。 这样理解就不容易犯错了。