Search code examples
javanumbersbigdecimalcumulative-sum

add BigDecimal in order to have a running total


I would like to pick your brians about BigDecimal.. I have a method which is supposed to have a add up a running total amount due. here it is:

private BigDecimal addUpTotal(BillRec bill, BigDecimal runningTotal) {
    BigDecimal result = new BigDecimal(0);

    if (bill.getBillInfo().getBillSummAmtSize() > 0) {
        for (int x = 0; x < bill.getBillInfo().getBillSummAmtSize(); x++) {
            if ("TotalAmtDue".equals(bill.getBillInfo().getBillSummAmt(x).getBillSummAmtCode().getCode().toString())) {
                result = runningTotal.add(bill.getBillInfo().getBillSummAmt(x).getAmt());                  
            }
        }
    }      
    return result;
}

the problem is how do I call this? meaning when I call it how do I keep track of the total? Note as you can see I am passing the runningTotal as a param but not sure how to keep the value in the method I would call this from.


Solution

  • I suspect you meant it to be something like this:

    private BigDecimal addUpTotal(BillRec bill, BigDecimal runningTotal) {
        if (bill.getBillInfo().getBillSummAmtSize() > 0) {
            for (int x = 0; x < bill.getBillInfo().getBillSummAmtSize(); x++) {
                if (...) {
                    runningTotal = runningTotal.add(...);
                }
            }
        }      
        return runningTotal;
    }
    

    You'd call that using a local variable to keep the running total:

    BigDecimal runningTotal = BigDecimal.ZERO;
    
    for (BillRec bill : bills) {
        runningTotal = addUpTotal(bill, runningTotal);
    }