How to add to BigDecimal

I have the following function, which iterates through an array, calls a method for each Return object that returns a BigDecimal that contains some value, for example. 20.45:

private String getTransactionTotals(Refund[] refunds) { BigDecimal total = new BigDecimal(0.00); /* * Itterates over all the refund objects and adds * their amount payables together to get a total */ for ( Refund refund : refunds ) { total.add(refund.getAmountPayable()); } total = total.setScale(2, RoundingMode.CEILING); return total.toString(); } 

The problem is that it always returns "0.00". I know that the array I'm passing is not null, and the values ​​that their getAmountPayable () 'functions are also non-zero. I don't know if I have been looking at this for too long, and I miss the obvious, some help would be greatly appreciated.

PS - 'getAmountPayble ()' returns a value of type BigDecimal

+6
source share
2 answers

You need to use the return value of add because BigDecimal is immutable. So you want:

 total = total.add(refund.getAmountPayable()); 

(Personally, I think this would be more obvious if the method was called plus , not add , but it doesn't matter).

+12
source

John Skeet's answer is correct. Here is the javadoc API for BigDecimal # add :

Returns a BigDecimal whose value is (this + augend) and whose scale is max (this.scale (), augend.scale ()).

0
source

Source: https://habr.com/ru/post/977808/


All Articles