Java 中 Math.rint() 和 Math.round() 之间的区别

2022-09-02 20:12:53

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


答案 1

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

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文章,简要比较和:http://www.coderanch.com/t/239803/java-programmer-OCPJP/certification/Difference-rint-methods-Math-classMath.rint()Math.round()


答案 2

Math.rint() 示例:2.50 位于 2.00 和 3.00 之间。Math.rint() 返回最接近的偶数双精度值。Math.rint(2.50) 返回 2.0。

Math.round() 示例:2.50 位于 2.00 和 3.00 之间。Math.round() 返回最接近的较高整数。Math.round(2.50) 返回 3