使用Java中的BigDecimal进行舍入模式 [英] Rounding mode with BigDecimal in Java

查看:248
本文介绍了使用Java中的BigDecimal进行舍入模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使用 RoundingMode.HALF_EVEN

BigDecimal value1 = new BigDecimal("4.5");
value1=value1.setScale(0, RoundingMode.HALF_EVEN);

BigDecimal value2 = new BigDecimal("6.5");
value2=value2.setScale(0, RoundingMode.HALF_EVEN);

System.out.println(value1+"\n"+value2);

显示 4 6 。在我看来它应该分别显示 5 7 ,因为丢弃的小数部分左边的数字(在这种情况下为5)奇数。在这种情况下,它执行 RoundingMode.HALF_UP

displays 4 and 6 respectively. It seems to me that it should display 5 and 7 respectively because the digit to the left of the discarded fractional part (which is 5 in this case) is odd. In this case, it performs RoundingMode.HALF_UP

如果是 RoundingMode.HALF_UP当丢弃的小数部分> = 0.5(这是真的)时执行 RoundingMode.UP ,否则执行 RoundingMode。执行DOWN

推荐答案

Javadoc


舍入模式向最近邻居舍入,除非两个
邻居都是等距的,在这种情况下,向着
邻居舍入

所以给出数字4.5,它在4到5之间的数字范围中间,当你打电话时:

So given the number 4.5, which falls right in the middle of the range of numbers between 4 and 5, when you call:

BigDecimal value1 = new BigDecimal("4.5").setScale(RoundingMode.ROUND_HALF_EVEN);

运行时需要确定哪个邻居也要舍入,也就是说,它应该舍入为4,或者到5?通常情况下,它会根据4.5更接近的值进行舍入,但在这种情况下,它接近 两个 邻居。它不是随意挑选最终结果,而是选择偶数。这是 ROUND_HALF_EVEN 的行为。如果你愿意,你可以指定 ROUND_HALF_UP ,最终结果将是5,而不是4.另外,请记住,关于如何舍入的决定是基于最终结果是什么(而不是大小数的小数部分,正如你似乎假设的那样)。

The runtime needs to figure out which neighbor to round too, aka, should it round to 4, or to 5? Normally it would round based on which value 4.5 is closer to, but in this case its close to both neighbors. Instead of arbitrarily picking the final result though, it picks the even number. This is the behavior of ROUND_HALF_EVEN. If you wanted to, you could specify ROUND_HALF_UP and the final result would have been 5, and not 4. Also, keep in mind that the determination about how to round is based on what the final result would be (and not on the decimal portion of the big decimal, as you seem to have assumed).

这篇关于使用Java中的BigDecimal进行舍入模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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