JDK-8223946 : NumberFormat.format() HALF_UP rounding is incorrect: 16.665 -> 16.66
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.text
  • Affected Version: 13
  • Priority: P3
  • Status: Resolved
  • Resolution: Not an Issue
  • Submitted: 2019-05-15
  • Updated: 2019-05-16
  • Resolved: 2019-05-15
Related Reports
Relates :  
Description
(submitting this on behalf of Roman Ushakov)

See this test:

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
 
class HalfUpBug {
    public static DecimalFormat createDecimalFormat(int accuracy) {
        DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.getDefault());
        DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
        symbols.setGroupingSeparator(' ');
        symbols.setDecimalSeparator('.');
        format.setDecimalFormatSymbols(symbols);
        format.setMinimumFractionDigits(accuracy);
        format.setMaximumFractionDigits(accuracy);
        return format;
    }
 
    public static void main(String[] args) {
        final DecimalFormat decimalFormat = createDecimalFormat(2);
        System.out.println(decimalFormat.format(16.665));
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        System.out.println(decimalFormat.format(16.665));
    }
}

On current jdk/jdk it produces:

16.66
16.66

...while users expect it to be 16.67.

It looks similar to already fixed JDK-8039915.
Comments
The closest binary representation of the double value 16.665 is: 16.66499999999999914734871708787977695465087890625 Thus rounding at the thousandths place will not round up in HALF_UP mode, because the value is '4'.
16-05-2019