3

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?

Community
  • 1
  • 1
Amit Kumar Gupta
  • 7,193
  • 12
  • 64
  • 90
  • 3
    Print `new BigDecimal(4.5805).toString()` and `new BigDecimal(4.4805).toString()` to see there is no bug here and this is behaving exactly like described in the linked question. – Tunaki Aug 10 '16 at 11:40

1 Answers1

4

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")));
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418