JDK-8227429 : Incorrect rounding with String.format()
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 8,11,13
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: generic
  • CPU: generic
  • Submitted: 2019-06-28
  • Updated: 2019-07-16
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.
Other
tbdUnresolved
Related Reports
Relates :  
Description
ADDITIONAL SYSTEM INFORMATION :
OSX, JDK 12,8

A DESCRIPTION OF THE PROBLEM :
Wrong rounding in formatter:
      double v3 = 0.00024649999999999997d;
       System.out.println(String.format("%.6f", v3));
       System.out.println(String.format("%.7", v3));
0.000247 (incorrect)
0.0002465

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
double v3 = 0.00024649999999999997d;
       System.out.println(String.format("%.6f", v3));
       System.out.println(String.format("%.7f", v3));

double v2 = .0002755d;
System.out.println(new DecimalFormat("#.######").format(v2));

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
0.000246
ACTUAL -
0.000247

---------- BEGIN SOURCE ----------
double v3 = 0.00024649999999999997d;
System.out.println(String.format("%.6f", v3));
System.out.println(String.format("%.7f", v3));
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
BigDecimal maybe, but it's slow

FREQUENCY : always



Comments
Not sure whether this is closer to [~naoto] or [~bpb] ....
12-07-2019

Possibly related to changes done for JDK-7131459.
09-07-2019

The double value 0.00024649999999999997 is represented in system as 0.00024649999999999997433997034335106945945881307125091552734375 , so the String.format() should have used Rounding.HALF_UP, according to which for 6 digits it should have been 0.000246 as output. But instead it is 0.000247 as output. If the double value 0.00024649999999999997 is cast as float , it is represented in system as 0.000246500014327466487884521484375 and then the Rounding for both 6 and 7 fraction digits seems to give the output we are getting now.
09-07-2019