6 Replies Latest reply on Oct 22, 2008 10:20 PM by 807589

BigDecimal Round Half Up  - Not Working Properly

BigDecimal's ROUND_HALF_UP method is producing some strange results for me. I'm trying to round off a double to decimal places.

Here is the description of the method from the API

"Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is >= .5; otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school."

However, I've found that if the discarded fraction =5 it rounds down, not up.

e.g.
``````bd = new BigDecimal(12.825);
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
double result = bd.doubleValue();``````
result=12.82!!!!

I noticed on IBM's list of JAVA fixes, it mentions a fix to BigDecimal's Round_Half_Up method but for older versions of Java (1.4). I'm running the newest version, but surely this is the same problem they're talking about.

• 1. Re: BigDecimal Round Half Up  - Not Working Properly
``````import java.math.*;

public class Test {
public static void main(String[] args) {
BigDecimal bd = new BigDecimal("12.825");
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
double result = bd.doubleValue();
System.out.println(result);
}
}``````
Use the constructor that takes a string. Read why the constructor that takes a double can be "somewhat unpredictable".: [http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#BigDecimal(double)]
• 2. Re: BigDecimal Round Half Up  - Not Working Properly
Try printing
System.out.println(new BigDecimal(12.825));
and
System.out.println(new BigDecimal("12.825"));
you should see a significant difference.
• 3. Re: BigDecimal Round Half Up  - Not Working Properly
``````import java.math.*;

public class Foo {
public static void main(String[] args) {
BigDecimal bd = new BigDecimal("12.825");
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
assert 12.83 == bd.doubleValue();
}

}``````
C:\>java -version
java version "1.6.0_07"
Java(TM) SE Runtime Environment (build 1.6.0_07-b06)
Java HotSpot(TM) Client VM (build 10.0-b23, mixed mode, sharing)

[EDIT] I've been "Handled!"

~
• 4. Re: BigDecimal Round Half Up  - Not Working Properly
Thanks for that. All sorted.
:)
• 5. Re: BigDecimal Round Half Up  - Not Working Properly
yawmark wrote:
[EDIT] I've been "Handled!"

~
Alien Abduction...