BigDecimal rounding problem using setScale()

Things aren't working the way I expect. I have the code:

    activeAmount.setScale(2,RoundingMode.HALF_UP);
    pensionAmount.setScale(2,RoundingMode.HALF_UP);
    interestAmount.setScale(2,RoundingMode.HALF_UP);
    distributionAmount.setScale(2,RoundingMode.HALF_UP);
    BigDecimal balance = pensionAmount.add(activeAmount).add(interestAmount).subtract(distributionA$
    balance.setScale(2,RoundingMode.HALF_UP);
    wrk = string12 + twoPlaces.format(balance);
    System.out.println("Balance             " + wrk.substring(wrk.length() - 12));
System.out.println("\n" + fourPlaces.format(balance));

And I get:

DROP TOTALS:
  Active               21,443.25  Last Active Deposit: 04/23/2011
  Pension             125,534.07
Total Contributions   146,977.32
  Interest              2,512.78  Current Interest Rate: 1.7003%
  Distribution        149,490.10
Balance                    -0.00

-0.0026

Why is the 0.0026 not rounded off to 2 decimal positions?
LVL 1
jmarkfoleyAsked:
Who is Participating?
 
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
The name of the method (setScale) is a bit misleading, but if you look at the Java docs for BigDecimal you will see that it mentions about BigDecimal's being immutable, so that setScale doesn't actually modify the original object, but it returns a new object with the scale set.

Try the following...

balance = balance.setScale(2, RoundingMode.HALF_UP);

0
 
jmarkfoleyAuthor Commented:
That did the trick! Thanks. I think I knew that once, but forgot.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.