我有以下代码:
BigDecimal result = BigDecimal.ZERO;
result.setScale(2, BigDecimal.ROUND_FLOOR); //1
BigDecimal amountSum;
// amount sum computation
BigDecimal amountByCurrency = amountSum.divide(32); //-0.04
result.add(amountByCurrency); //2
在
//1
行之后比例仍然是 0。为什么?因此,//2
评估不会影响结果。怎么了?
最佳答案
#setScale
documentation 的重要部分是这样的:
Note that since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, contrary to the usual convention of having methods named setX mutate field X. Instead, setScale returns an object with the proper scale; the returned object may or may not be newly allocated.
(强调)
因此,您代码中的这一行不会更改
result
实例:result.setScale(2, BigDecimal.ROUND_FLOOR); //1
要么将其更改为:
result = result.setScale(2, BigDecimal.ROUND_FLOOR);
用新的实例覆盖实例,或创建一个新变量并使用它代替
result
:BigDecimal scaledResult = result.setScale(2, BigDecimal.ROUND_FLOOR);
顺便说一句:这同样适用于这一行:
result.add(amountByCurrency); //2
您需要将
BigDecimal
调用返回的 #add
实例存储在一个变量中。
关于java - BigDecimal 刻度不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28216251/