java - Java 中 Math.rint() 和 Math.round() 的区别

标签 java rounding

Math.rint()Math.round() 有什么区别?

最佳答案

Math.rint()Math.round() 有几个不同之处,但对 Java 应用程序的业务逻辑影响最大的是方式它们处理边界上的整数舍入(例如 4.5 位于 45 的边界上)。考虑以下代码片段和输出:

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/

相关文章:

java - 按下按键时使用计时器

java - Android studio 如何一次创建注册屏幕

java - Stripes URLBinding 默认为错误的 URL

Java - 如何将计算语句结果四舍五入到两位有效数字

java - 带偏移量的 double 最接近的倍数 java

java - 如何检查文件中的某个单词是否有该单词

java - ehcache memorystoresize 和 diskstoresize

java - 在 Java 中将整数四舍五入为特定整数

python - 防止在 Python 中四舍五入为零

algorithm - 四舍五入到任意数量的有效数字