为什么在bigdecimal划分的0.454至0.5的圆形分区中会进行圆形模式。
圆形模式falt_even
应该圆形a(十进制)数字以5结束至最接近的偶数 的精确数字(例如,4.5舍入4.5,而5.5则是四舍五入的。到6)。
现在,Java的bigdecimal
的部门似乎不遵守该规则。以下代码将其转到0.45至0.5:
import java.math.*;
class Round {
public static void main(String[] args) {
BigDecimal five = BigDecimal.valueOf(5);
BigDecimal eleven = BigDecimal.valueOf(11);
BigDecimal x = five.divide(eleven, 1, RoundingMode.HALF_EVEN);
System.out.println(x);
}
}
输出0.5
请注意,5/11 = 0.4545454545 ...因此,当查看小数点后的前两个数字时,0.45,我们显然希望看到它被舍入到最近的邻居,即IE,即0.40,而不是0.50。
谁能解释一下?
(如果很重要,我正在运行java -version
= openjdk版本“ 11.0.15” 2022-04-19)
注意:
- 这不是关于在之前 大数的价值;的确 当使用字符串构造函数时,结果也没有变化,
BigDecimal five = new BigDecimal("5");
BigDecimal eleven = new BigDecimal("11");
BigDecimal x = five.divide(eleven, 1, RoundingMode.HALF_EVEN);
- 它也不取决于我们圆形的比例(只要尺度为奇数),并且您可以将数字扩展到数字(例如,循环500/11)。
The rounding mode HALF_EVEN
is supposed to round a (decimal) number ending in 5 to the closest even less precise number (e.g., 4.5 is rounded to 4, whereas 5.5 is rounded to 6).
Now, it seems that Java's division of BigDecimal
is not obeying that rule; the following code gets it to round 0.45 to 0.5:
import java.math.*;
class Round {
public static void main(String[] args) {
BigDecimal five = BigDecimal.valueOf(5);
BigDecimal eleven = BigDecimal.valueOf(11);
BigDecimal x = five.divide(eleven, 1, RoundingMode.HALF_EVEN);
System.out.println(x);
}
}
Output 0.5
Note that 5/11 = 0.4545454545... so when looking at the first two digits after the decimal point, 0.45, we clearly would want to see that rounded to the nearest even neighbor, i.e. to 0.40, not 0.50.
Can anyone explain this?
(In case it matters, I'm running java -version
= openjdk version "11.0.15" 2022-04-19)
Note:
- This is not about rounding before getting a value into the BigDecimal; indeed
the result is unchanged when using the string constructor
BigDecimal five = new BigDecimal("5");
BigDecimal eleven = new BigDecimal("11");
BigDecimal x = five.divide(eleven, 1, RoundingMode.HALF_EVEN);
- It also doesn't depend on the scale at which we round (as long as scale is odd), and you can scale the number up (e.g., round 500/11).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
heft_even :
因此,首先需要确定两个邻居是否等距。
这不足以确定该值是否等距是两个邻居的等距,在这种情况下为0.4和0.5。在这种情况下,我们需要查看另外一位数字。
在5/11的情况下,5/11的接近0.5(距离= 0.045454545 ...),而不是0.4(距离= 0.0545454 ...),因此,“不应用“朝向邻居的圆形往返”,并且“圆形”的圆形。朝向“最近的邻居”” 是。
HALF_EVEN
:So it is needed to first decide whether both neighbours are equidistant.
That's not sufficient to determine whether the value is equidistant is equidistant to both neighbours, which in this case is 0.4 and 0.5. We need to look at one more digit in this case.
In the case of 5/11, 5/11 is closer to 0.5 (distance = 0.045454545...) than to 0.4 (distance = 0.0545454...), so "round towards the even neighbor" is not applied, and "round towards the 'nearest neighbor'" is.