I have the following function that itterates over an array, calls a method on each 'Refund' object that returns a BigDecimal that contains some value e.g. 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 for a fact that the array that I'm passing is not null, and the values that their 'getAmountPayable()' function retuns are also not null or equal to 0. I don't know if I've been staring at this for too long and I'm missing the obvious, some help would greatly be appreciated.
PS - 'getAmountPayble()' return a value of type BigDecimal
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 have been more obvious if the method had been called plus
rather than add
, but never mind.)
See more on this question at Stackoverflow