Amit Gupta Amit Gupta - 3 months ago 12
Java Question

Java 8 DecimalFormat gives inconsistent output

JDK 8

DecimalFormat x = new DecimalFormat("0.000");
System.out.println(x.format(4.4804));
System.out.println(x.format(4.4805));
System.out.println(x.format(4.5805));
System.out.println(x.format(4.5804));


Output

4.480
4.481
4.580
4.580


I am aware about the JDK7 bug. But even in JDK 8 it is not consistent. am I doing something wrong?

Answer

As suggested by the comment to the question, your observed results are caused by your numeric literals being interpreted as double values which may not be represented exactly, e.g.,

System.out.println(new BigDecimal(4.4805).toString());

produces

4.48050000000000014921397450962103903293609619140625

which is then rounded to 4.481 because it is just past the half-way point between 4.480 and 4.481. You will see more consistent results if you tweak your code sample to

DecimalFormat x = new DecimalFormat("0.000");
System.out.println(x.format(new BigDecimal("4.4804")));
System.out.println(x.format(new BigDecimal("4.4805")));
System.out.println(x.format(new BigDecimal("4.5805")));
System.out.println(x.format(new BigDecimal("4.5804")));
Comments