BigDecimal 中 Divide 方法的 Scale()
new BigDecimal("37146555.53880000").divide(new BigDecimal("1000000")).scale()
这将返回 10
。但根据 API,divide
方法:
返回一个 BigDecimal,其值为 (这个/除数),以及谁的首选 比例尺是 (this.scale() - 除数.scale());
因此,在本例中,37146555.53880000
的小数位数为 8
,1000000
的小数位数为 0
。因此结果的比例应为 8
,而不是 10
。
我在这里缺少什么?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际结果是 37.1465555388,其小数位数必须为 10 才能准确。
JavaDoc 所说的是首选比例是差异,这意味着如果结果实际上不需要为 10,那么它会尝试将其变为 8。例如,如果您除以 2,其比例也是 0 ,结果将为 18573277.76940000(标度 8)。
编辑:小加法 - 您可以通过使用重载的除法方法强制除法到一定比例:
divide(BigDecimal, RoundingMode)
这将给出一个BigDecimal
如果结果实际上需要更多的小数位才能准确,则使用指定的舍入方法舍入此值的比例和值。divide(BigDecimal, scale, RoundingMode)
将给出具有指定比例的BigDecimal
,并根据需要按指定方法舍入值。如果您除以一个您知道会导致重复小数的数字,例如 3 (1/3 = 0.333333...),这可能很有用,因为如果发生这种情况,简单的除法将引发异常。将其限制为最大小数位数将帮助您避免异常,但会使您的计算不太精确。
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 addition - you can force the division to a certain scale by using the overloaded divide methods:
divide(BigDecimal, RoundingMode)
that will give aBigDecimal
with scale ofthis
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 aBigDecimal
with specified scale, and value rounded by specified method if needed.This might be useful if you're 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.divide(BigDecimal, int, int)
。It says "preferred scale" not "definitely will be scale".
To be absolutely sure, I would use
BigDecimal.divide(BigDecimal, int, int)
.