Math.ceil()、Math.floor()和Math.round()
这三个方法分别遵循下列舍入规则:
1. Math.ceil()返回大于等于参数x的最小整数,即对浮点数向上取整.
实例:
println(Math.ceil(0))
println(Math.ceil(0.4))
println(Math.ceil(0.5))
println(Math.ceil(0.7))
println(Math.ceil(-1))
println(Math.ceil(-0.2))
println(Math.ceil(-0.6))
结果:
0.0
1.0
1.0
1.0
-1.0
-0.0
-0.0
2. Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;
println(Math.floor(0))
println(Math.floor(0.4))
println(Math.floor(0.5))
println(Math.floor(0.7))
println(Math.floor(-1))
println(Math.floor(-0.2))
println(Math.floor(-0.6))
结果:
0.0
0.0
0.0
0.0
-1.0
-1.0
-1.0
3. Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数(这也是我们在数学课上学到的舍入规则)。
println(Math.round(0))
println(Math.round(0.4))
println(Math.round(0.5))
println(Math.round(0.7))
println(Math.round(-1))
println(Math.round(-0.2))
println(Math.round(-0.6))
结果:
0
0
1
1
-1
0
-1