JDK-8066560 : (fmt) Formatter printf rounding error (double rounding up) for double values close to but below tie
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util
  • Affected Version: 8,9
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: generic
  • CPU: generic
  • Submitted: 2014-12-03
  • Updated: 2019-12-18
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
Related Reports
Relates :  
Relates :  
PrintStream.printf  (i.e. java.util.Formater printf) is suffering the same kind of rounding problems
that was found in java.text.DecimalFormat/DigitList : erroneous double rounding

The following code:
  double d = 12.225d;
  System.out.println("BigDecimal output for " + d + " -> " + new BigDecimal(d).toString());
  System.out.printf("test %1$.2f \n", 12.225d);

shows that printf will wrongly round up, following  half-up rounding rule specified by
Format string syntax in Formatter.

Result from the above is the following output :
> BigDecimal output for 12.225 -> 12.2249999999999996447286321199499070644378662109375
> test 12.23 
the printf call shoud provide "test 12.22" since the double d is below the tie.
We noticed the reported behavior at Google.

java.util.Formatter stack uses binaryToAsciiConverter from sun.misc.FloatingDecimal to convert the double to decimal digits, which in turn calls the dtoa algorithm, which in the case below rounded up to 12.225. Thus Formatter uses an *already rounded-up* value from FormattedFloatingDecimal, causing a double rounding-up error in the final result. This is similar to bug JDK-7131459, restricted to the HALF_UP rounding case (due to Format string syntax rounding rules). Other tricky corner cases that might show up must be checked.