unable to sum BigDecimal in for loop java

I am trying to sum BigDecimals from a list into one result but my result remains zero even after the for loop is finished.

I am trying like:

BigDecimal result = BigDecimal.ZERO;
for (TaxSummaryType offerTaxSummary : offerTaxSummaryList) {
   BigDecimal tax = offerTaxSummary.getTotalTaxAmount().getValue(); 
   //iteration i). 1266.48
   //iteration ii). 1266.48
   //iteration iii). 1706.58
   result.add( tax );
}
System.out.println( result ); //output: 0

Please help me resolve it. Thank you.

>Solution :

BigDecimal is immutable. The add method does not change the existing result but returns a new instance.

Your code however does not use that return value but ignores it.

Fix it by using

result = result.add(tax);

Leave a Reply