在BigDecimal中划分方法的Scale() [英] Scale() of Divide method in BigDecimal

查看:1008
本文介绍了在BigDecimal中划分方法的Scale()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(新的BigDecimal(1000000))。scale()


这将返回 10 。但根据API,除以方法:

lockquote>

返回一个BigDecimal,其值是
(this / divisor),其首选的
比例是(this.scale() -
divisor.scale());

所以在这种情况下, 37146555.53880000's 的比例是 8 1000000 的比例是 0 。所以结果应该是 8 ,而不是 10



我在这里错过了什么?



谢谢

>实际结果是37.1465555388,它的规模必须是10才能确切。

JavaDoc所说的是,首选的比例是不同的意思,如果结果不是实际上需要是10,那么它会试图做到这一点8.例如,如果你将除以2,其规模也是0,结果将是18573277.76940000(规模8)。



编辑:小adition - 你可以通过使用重载的分割方法强制司到一定的规模:


  • divide(BigDecimal,RoundingMode)将给出 BigDecimal ,其比例为 ,如果结果确实需要更多的小数,那么使用指定的四舍五入方法进行四舍五入。

  • $ C> dividediv ide(BigDecimal,scale,RoundingMode),它会给出一个带有指定比例的 BigDecimal ,如果需要,可以通过指定方法舍入值。




如果您除以您知道的数字可能导致重复的小数位,如3(1/3 = 0.333333 .. )因为,如果发生这种情况,简单的鸿沟就会抛出异常。将其限制为最大小数位数将有助于避免出现异常,但会使计算精度下降。


new BigDecimal("37146555.53880000").divide(new BigDecimal("1000000")).scale()

This returns 10. But according to the API, the divide method:

Returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() - divisor.scale());

So in this case, 37146555.53880000's scale is 8, and 1000000's scale is 0. So the result should have a scale of 8, not 10.

What am I missing here?

Thanks

解决方案

The actual result is 37.1465555388 whose scale must be 10 for it to be exact.

What the JavaDoc says is that the preferred scale is the difference meaning that if the result didn't actually need to be 10, then it would try to make it 8. For example if you would have divided by 2, whose scale is also 0, the result would have been 18573277.76940000 (scale 8).

EDIT: small adition - you can force the division to a certain scale by using the overloaded divide methods:

  • divide(BigDecimal, RoundingMode) that will give a BigDecimal with scale of this and value rounded using the specified rounding method if the result would actually need more decimals to be exact.

  • dividedivide(BigDecimal, scale, RoundingMode) that will give a BigDecimal with specified scale, and value rounded by specified method if needed.

This might be useful if your dividing by a number you know can cause repeating decimals, like 3 (1/3 = 0.333333...) since, if that happens, the simple divide will throw an exception. Bounding it to a maximum number of decimals will help you avoid the exception but will make your computations less precise.

这篇关于在BigDecimal中划分方法的Scale()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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