Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 DecimalFormat gives inconsistent output [duplicate]

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?

like image 856
Amit Kumar Gupta Avatar asked Apr 26 '26 20:04

Amit Kumar Gupta


1 Answers

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")));
like image 112
Gord Thompson Avatar answered Apr 28 '26 09:04

Gord Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!