BigDecimal 比例不起作用
BigDecimal scale not working
我有以下代码:
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
评估不会影响结果。怎么了?
您更改了 result
的比例,但未更改 amountSum
或 amountByCurrency
的比例,因此当您使用此变量操作时,您使用的是比例 0。
如果我没记错的话,有一个 "global" 方法可以在创建 BigDecimal 时设置默认比例。你应该使用这种方法,或者通过变量设置比例变量。
#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
您需要将 #add
调用返回的 BigDecimal
实例存储在一个变量中。
我有以下代码:
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
评估不会影响结果。怎么了?
您更改了 result
的比例,但未更改 amountSum
或 amountByCurrency
的比例,因此当您使用此变量操作时,您使用的是比例 0。
如果我没记错的话,有一个 "global" 方法可以在创建 BigDecimal 时设置默认比例。你应该使用这种方法,或者通过变量设置比例变量。
#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
您需要将 #add
调用返回的 BigDecimal
实例存储在一个变量中。