Search code examples
javabigdecimal

BigDecimal Substract with negative result


I have this code:

public BigDecimal getDifference() {
    BigDecimal total = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_DOWN);

    for (Order order : orders) {
        BigDecimal originalCost= order.getOriginalValue();

        BigDecimal nweCost= order.getNewValue();

        BigDecimal diff = newValue.substract(originalValue);

        total.add(diff);
    }

    return total;
}

I am testing with originalCost > newCost but total is always 0. I took a snapshot of the debugger at the line total.add(diff):

debugger

Does anybody know what I am doing wrong?

Thanks.


Solution

  • total = total.add(diff);
    

    Immutable type, like String.

    Some IDEs give a warning.