Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same decimal, different rounding results? [duplicate]

Two decimal places are kept, the fractional part is the same, and the result is inconsistent

jdk1.8.0_162

DecimalFormat df = new DecimalFormat("##.00");
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println("1.985 ≈ " + df.format(1.985));
System.out.println("23.985 ≈ " + df.format(23.985));
1.985 ≈ 1.99
23.985 ≈ 23.98

The output is as above, and should be the same as the fractional part.

like image 548
Jason Avatar asked Aug 05 '26 03:08

Jason


1 Answers

This is how floating point types work. They can be an approximation. The approximations for your two numbers are not the same since they are not the same numbers. The one number might be 1.985000000000001 and the other number might be 23.98499999999999 internally. See also here.

like image 199
cmoetzing Avatar answered Aug 07 '26 17:08

cmoetzing