Solved

# BigDecimal rounding problem using setScale()

Posted on 2011-10-19
324 Views
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);
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
Question by:jmarkfoley

LVL 35

Accepted Solution

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

That did the trick! Thanks. I think I knew that once, but forgot.
0

## Featured Post

### Suggested Solutions

FizzBuzz challenge 9 64
hasOne  challenge 59 63
Modeling a class in java 5 22
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input: