1. ## 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.

Java Code:
```BigDecimal total = BigDecimal.ZERO.setScale(2);
for(Payment payment : payments) {
BigDecimal payAmt = payment.getPaymentAmt();
}```
While debugging, I see that in the BigDecimal add method, I'm hitting this exit point.

Java 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:

Java Code:
```BigDecimal total = BigDecimal.ZERO.setScale(2);
BigDecimal paymentAmt = Payment.getPaymentAmt();
Last edited by ShoeNinja; 12-01-2009 at 06:51 PM. Reason: Solved.

2. Member
Join Date
Mar 2011
Posts
2
Rep Power
0
What was the solution?

I am having the same problem.

3. Moderator
Join Date
Apr 2009
Posts
11,302
Rep Power
18
They gave the solution at the end...

4. Member
Join Date
Mar 2011
Posts
2
Rep Power
0
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:

Java Code:
```BigDecimal total = BigDecimal.ZERO.setScale(2);
for(Payment payment : payments) {
BigDecimal payAmt = payment.getPaymentAmt();
}```

5. Moderator
Join Date
Apr 2009
Posts
11,302
Rep Power
18
Which is what the edit summarised.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•