?
Solved

BigDecimal rounding problem using setScale()

Posted on 2011-10-19
2
Medium Priority
?
354 Views
Last Modified: 2012-08-13
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?
0
Comment
Question by:jmarkfoley
2 Comments
 
LVL 36

Accepted Solution

by:
mccarl earned 2000 total points
ID: 36997429
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
 
LVL 1

Author Comment

by:jmarkfoley
ID: 36997503
That did the trick! Thanks. I think I knew that once, but forgot.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month16 days, 21 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question