• 12-01-2009, 06:41 PM
ShoeNinja
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);```
• 03-14-2011, 11:24 AM
leet3lite
What was the solution?

I am having the same problem.
• 03-14-2011, 11:45 AM
Tolls
They gave the solution at the end...
• 03-14-2011, 01:16 PM
leet3lite
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 re-assign 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); }```
• 03-14-2011, 01:19 PM
Tolls
Which is what the edit summarised.