Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8313434

java.text.DecimalFormat rounding section is under specified

XMLWordPrintable

      There are behavioral differences between j.util.Formatter vs j.text.DecimalFormat for what one would expect the same answer,

      For example,

      var df = new DecimalFormat("0.00000");
      df.setRoundingMode(RoundingMode.HALF_UP);
      df.format(0.002485); // -> "0.00248"
      String.format("%.5f", 0.002485); // -> "0.00249"

      This is made further confusing since DecimalFormat has minimal specification regarding rounding, which is "DecimalFormat provides rounding modes defined in RoundingMode for formatting. By default, it uses RoundingMode.HALF_EVEN."

      At a minimum, DecimalFormat needs to have a overhaul of the current rounding section to address the 3 main issues
      - No spec regarding what type of format, the rounding is performed under, causing confusion in the past (JDK-7131459, etc.).
      - No spec regarding the precision of the DecimalFormat beyond the pattern. If I format a fractional value with 50 fractional digits, even if my pattern supports that many digits, I lose most of the precision
      - No spec when formatting to less digits than the input value with certain rounding modes

      These should all be added to a new rounding mode section.

      As to the discrepancy in behavior between Formatter and DecimalFormat, DecimalFormat has had this discrepancy for 10+ years, which raises concerns for compatibility issues if the classes are aligned. It is safest to not align the classes, however, standardizing the behavior for a future LTS release is a possibility.

            jlu Justin Lu
            jlu Justin Lu
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: