Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading