I am rewriting an old Java 6 Program written to perform some scientific calculations in Java 8 and stuck up in this situation where I'm getting different results for rounding operation.
Java 6 is rounding an input like 0.499999999999999999994
to 1
but Java 8 is making it 0
. I'm not able to understand the problem here.
For Instance:
private void foo() {
System.out.println(Math.round(0.499999999999999999994));
}
The above code behaves differently for different Java versions.
It would be great if someone could shed some light on this issue.
I think you stumbled on a known bug in Java 6
which was later fixed in Java 7. This explains the weird code behaviour in Java 6
and Java 8
.
Bug Info:
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6430675
More information and beautiful explanation by @OliverCharlesworth can be found in this post:
Why does Math.round(0.49999999999999994) return 1
Excerpt from his post:
In Java 6 (and presumably earlier), round(x) is implemented as floor(x+0.5). This is a specification bug, for precisely this one pathological case. Java 7 no longer mandates this broken implementation.