Scale() of Divide method in BigDecimal

独自空忆成欢 提交于 2019-12-05 06:25:49
Andrei Fierbinteanu

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.

  • divide(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.

These scales are the ones used by the methods which return exact arithmetic results; except that an exact divide may have to use a larger scale since the exact result may have more digits. For example, 1/32 is 0.03125.

hvgotcodes

It says "preferred scale" not "definitely will be scale".

To be absolutely sure, I would use BigDecimal.divide(BigDecimal, int, int).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!