Math.ceil()
向上取整
- 对于给定的数
x
,Math.ceil(x)
表示大于或等于x
的整数。请看示例:
System.out.println(Math.ceil(10)); // 10.0
System.out.println(Math.ceil(10.5)); // 11.0
System.out.println(Math.ceil(-10.5)); // -10.0
注意: 在负半轴上可能有人不是很明白,我们可以看数学上的比较-10 > -10.5
,即-10
是-10.5
的上限。
Math.floor()
向下取整
- 对于给定的数
x
,Math.floor(x)
表示小于或等于x
的整数。请看示例:
System.out.println(Math.floor(10)); // 10.0
System.out.println(Math.floor(10.5)); // 10.0
System.out.println(Math.floor(-10.5)); // -11.0
Math.round()
四舍六入五成双
-
规则:
- 被修约的数字小于5时,该数字舍去,即四舍
- 被修约的数字大于5时,则进位,即六入
- 被修约的数字等于5时,要看5前面的数字,若是奇数则进位,若是偶数则将5舍掉,即修约后末尾数字都成为偶数;若5的后面还有不为“0”的任何数,则此时无论5的前面是奇数还是偶数,均应进位,即五成双的情况。
-
上面的规则不是很好理解,我们可以这样去计算:对于给定的数
x
,Math.round(x)
表示为Math.floor(x + 0.5)
,请看示例:
System.out.println(Math.round(10.4)); // 10
System.out.println(Math.round(10.6)); // 11
System.out.println(Math.round(-10.4)); // -10
System.out.println(Math.round(-10.6)); // -11
System.out.println(Math.round(10.5)); // 11
System.out.println(Math.floor(10.5 + 0.5)); // 11.0
System.out.println(Math.round(-10.5)); // -10
System.out.println(Math.floor(-10.5 + 0.5)); // -10.0