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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With