
Adding BigDecimals
I'm trying to add several BigDecimals in a for loop. For some reason, I'm getting 0 on the other end of the loop.
Code:
BigDecimal total = BigDecimal.ZERO.setScale(2);
for(Payment payment : payments) {
BigDecimal payAmt = payment.getPaymentAmt();
total.add(payAmt);
}
While debugging, I see that in the BigDecimal add method, I'm hitting this exit point.
Code:
boolean lhsIsZero = lhs.signum() == 0;
boolean augendIsZero = augend.signum() == 0;
if (lhsIsZero  augendIsZero) {
int preferredScale = Math.max(lhs.scale(), augend.scale());
BigDecimal result;
// Could use a factory for zero instead of a new object
if (lhsIsZero && augendIsZero)
return new BigDecimal(BigInteger.ZERO, 0, preferredScale);
.sugnum() is not 0 for both the operands when I look at them just before add is called so I'm not sure why I would hit this return statement.
Any ideas?
EDIT:
BigDecimal.add() returns a BigDecimal. So it has to be something like:
Code:
BigDecimal total = BigDecimal.ZERO.setScale(2);
BigDecimal paymentAmt = Payment.getPaymentAmt();
total = total.add(paymentAmt);

What was the solution?
I am having the same problem.

Read the post.
They gave the solution at the end...

I read the whole post, but didn't understand it. The code at the top has a different algorithm and semantic logic to the second.
But I finally figured out what he was trying to say: BigDecimal is immutable (of course!), so you have to reassign the value. The code therefore would have to look like this:
Code:
BigDecimal total = BigDecimal.ZERO.setScale(2);
for(Payment payment : payments) {
BigDecimal payAmt = payment.getPaymentAmt();
[B][COLOR="Red"]total = [/COLOR][/B]total.add(payAmt);
}

Which is what the edit summarised.