Math.rint()
和 Math.round()
有什么区别?
最佳答案
Math.rint()
和 Math.round()
有几个不同之处,但对 Java 应用程序的业务逻辑影响最大的是方式它们处理边界上的整数舍入(例如 4.5
位于 4
和 5
的边界上)。考虑以下代码片段和输出:
double val1 = 4.2;
double val2 = 4.5;
System.out.println("Math.rint(" + val1 + ") = " + Math.rint(val1));
System.out.println("Math.round(" + val1 + ") = " + Math.round(val1));
System.out.println("Math.rint(" + val2 + ") = " + Math.rint(val2));
System.out.println("Math.round(" + val2 + ") = " + Math.round(val2));
System.out.println("Math.rint(" + (val2 + 0.001d) + ") = " + Math.rint(val2 + 0.001d));
System.out.println("Math.round(" + (val2 + 0.001d) + ") = " + Math.round(val2 + 0.001d));
输出:
Math.rint(4.2) = 4.0
Math.round(4.2) = 4
Math.rint(4.5) = 4.0
Math.round(4.5) = 5
Math.rint(4.501) = 5.0
Math.round(4.501) = 5
如您所见,Math.rint(4.5)
实际上是向下舍入,而 Math.round(4.5)
是向上舍入,这一点值得指出。然而,在所有其他情况下,它们都表现出我们所期望的相同舍入规则。
这是一篇有用的 Code Ranch 文章,它简要比较了 Math.rint()
和 Math.round()
:http://www.coderanch.com/t/239803/java-programmer-OCPJP/certification/Difference-rint-methods-Math-class
关于java - Java 中 Math.rint() 和 Math.round() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37256550/