BigDecimal scale not working

半城伤御伤魂 提交于 2019-12-11 03:15:38

问题


I have the following code:

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

After line //1 scale is still 0. Why? So, the //2 evaluation doesn't affect to the result. What's wrong?


回答1:


The important part of the #setScale documentation is this:

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.

(emphasis added)

Therefore, this line in your code won't change the result instance:

result.setScale(2, BigDecimal.ROUND_FLOOR); //1

Either change it to:

result = result.setScale(2, BigDecimal.ROUND_FLOOR);

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

You need to store the returned BigDecimal instance of the #add call in a variable.




回答2:


You have changed the scale of result, but not the scale of amountSum or amountByCurrency, so when you operate with this variables you are working with scale 0.

If I remember well, there is a "global" method to set the default scale when you create a BigDecimal. You should use this method, or set the scale variable by variable.



来源:https://stackoverflow.com/questions/28216251/bigdecimal-scale-not-working

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