本文介绍了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
评估不会影响结果.怎么了?
After line //1
scale is still 0. Why? So, the //2
evaluation doesn't affect to the result. What's wrong?
推荐答案
是这样的:
The important part of the #setScale
documentation is this:
(添加了重点)
因此,代码中的这一行不会更改result
实例:
Therefore, this line in your code won't change the result
instance:
result.setScale(2, BigDecimal.ROUND_FLOOR); //1
将其更改为:
result = result.setScale(2, BigDecimal.ROUND_FLOOR);
用新实例覆盖实例,或创建一个新变量并使用它代替result
:
to overwrite the instance with the new one, or create a new variable and use that instead of result
:
BigDecimal scaledResult = result.setScale(2, BigDecimal.ROUND_FLOOR);
顺便说一句:这条线也一样:
Btw: the same applies to this line:
result.add(amountByCurrency); //2
您需要将返回的#add
调用的BigDecimal
实例存储在变量中.
You need to store the returned BigDecimal
instance of the #add
call in a variable.
这篇关于BigDecimal刻度不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!