Java中Math.rint()和Math.round()之间的区别 [英] Difference between Math.rint() and Math.round() in Java

查看:67
本文介绍了Java中Math.rint()和Math.round()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

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

Math.rint() and Math.round() have several differences, but the one which might impact the business logic of a Java application the most is the way they handle rounding of integers which are on a boundary (e.g. 4.5 is on the boundary of 4 and 5). Consider the following code snippet and output:

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)则是四舍五入的,这一点值得指出.但是,在所有其他情况下,它们都表现出我们期望的相同舍入规则.

As you can see, Math.rint(4.5) actually rounds down, while Math.round(4.5) rounds up, and this deserves to be pointed out. However, in all other cases, they both exhibit the same rounding rules which we would expect.

这是一篇有用的Code Ranch文章,简要比较了 Math.rint() Math.round():

Here is a useful Code Ranch article which briefly compares Math.rint() and Math.round(): http://www.coderanch.com/t/239803/java-programmer-OCPJP/certification/Difference-rint-methods-Math-class

这篇关于Java中Math.rint()和Math.round()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆