在Java中使用DecimalFormat进行舍入 [英] Rounding with DecimalFormat in Java
问题描述
让我们看看Java中的以下语句。
Let's look at the following statements in Java.
System.out.println(new DecimalFormat("0").format(2.4)); //returns 2
System.out.println(new DecimalFormat("0").format(2.5)); //returns 2 <---Concentrate here
System.out.println(Math.round(2.5)); //returns 3
System.out.println(new DecimalFormat("0").format(2.6)); //returns 3
System.out.println(new DecimalFormat("0").format(3.5)); //returns 4
在上述声明中,除以下情况外,所有其他情况都很明显。
In the above statements, all other cases are obvious except the following.
System.out.println(new DecimalFormat("0").format(2.5));
它应返回 3
但它返回 2
。怎么样?
It should return 3
but it returns 2
. How?
推荐答案
这是故意行为。从文档:
舍入
Rounding
DecimalFormat使用半偶数舍入(请参阅ROUND_HALF_EVEN)进行格式化。
DecimalFormat uses half-even rounding (see ROUND_HALF_EVEN) for formatting.
关于 ROUND_HALF_EVEN :
舍入模式向最近邻居舍入,除非两个邻居都是等距的,在这种情况下,向着邻居走去。如果丢弃的分数左边的数字是奇数,则表现为ROUND_HALF_UP;如果它是偶数,则表现为ROUND_HALF_DOWN。请注意,这是一种舍入模式,可以在一系列计算中重复应用时最小化累积误差。
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.
这也称为银行家舍入。
Math.Round
使用以下公式,即正常舍入:
Math.Round
on the other hand uses the following formula, which is "normal" rounding:
(long)Math.floor(a + 0.5d)
这篇关于在Java中使用DecimalFormat进行舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!