Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal scale not working

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?

like image 762
St.Antario Avatar asked Dec 15 '22 17:12

St.Antario


1 Answers

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.

like image 133
Tom Avatar answered Jan 01 '23 22:01

Tom