BigDecimal HALF_UP舍入问题 [英] BigDecimal HALF_UP rounding issue

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

问题描述

我试图使用scale = 3和HALF_UP舍入模式来舍入0.14049并希望看到舍入值= 0.141但是得到0.140。

I am trying to round 0.14049 using scale=3 and HALF_UP rounding mode and hoping to see rounded value = 0.141 but getting 0.140 instead.

根据我的理解最后一个十进制数字9应该向上舍入4到5,当使用比例3时,它应该向上舍入0到1,我应该看到0.141。

As per my understanding the last decimal digit 9 should round up the 4 to 5 and that should in-turn round up 0 to 1 when using scale 3 and i should see 0.141.

这是一个BigDecimal setScale方法中的错误或我对Rounding的期望是错误的。如何获得类似于0.141而不是0.140的舍入值?

Is that a bug in BigDecimal setScale method or my expectation of Rounding is wrong. How can I get rounded values similar to 0.141 and not 0.140?

BigDecimal bd=new BigDecimal("0.14049");
BigDecimal normalizedField = field.setScale(3, RoundingMode.HALF_UP);
System.out.println(normalizedField);
// Output = 0.140


推荐答案


根据我的理解,最后一个十进制数字9应该向上舍入4到5,当使用比例3时,它应该反过来向上舍入0到1,我应该看到0.141。

As per my understanding the last decimal digit 9 should round up the 4 to 5 and that should in-turn round up 0 to 1 when using scale 3 and i should see 0.141.

这种理解是不正确的。舍入不是一个迭代过程。只考虑比例位置后的第一个数字,而不是整个数字链。在你的情况下,数字是4,所以它被转换为零。

This understanding is incorrect. Rounding is not an iterative process. Only the first digit after the scale position is considered, not the whole chain of digits. In your case, the digit is 4, so it gets converted down to zero.

这篇关于BigDecimal HALF_UP舍入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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