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

Overriding toString in java.math.BigDecimal may cause java.lang.NumberFormatExce

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 8
    • 7u60
    • core-libs
    • x86
    • windows_7

      FULL PRODUCT VERSION :
      java version "1.7.0_60"
      Java(TM) SE Runtime Environment (build 1.7.0_60-b19)
      Java HotSpot(TM) Client VM (build 24.60-b09, mixed mode, sharing)

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows [Version 6.1.7601]

      A DESCRIPTION OF THE PROBLEM :
      In case toString in BigDecimal has been overriden a call to doubleValue or floatValue might not work.
      This is due to the fact that the returned value depends on what is returned from toString and this value is not forced to be fetched from BigDecimal but rather from anywhere in an inheritance tree.

      BigInteger suffers from the same problem.

      As an added side note there is a comment in the code stating
      // Somewhat inefficient, but guaranteed to work.
      This is in other words not completely true as this error report show. ;-)

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      No exception.
      ACTUAL -
      Amount [amount=1.23]
      Exception in thread "main" java.lang.NumberFormatException: For input string: "Amount [amount=1.23]"
      at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250)
      at java.lang.Double.parseDouble(Double.java:540)
      at java.math.BigDecimal.doubleValue(BigDecimal.java:3136)
      at FailingBigDecimal.main(FailingBigDecimal.java:9)


      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.math.BigDecimal;
      import java.math.BigInteger;

      public class FailingBigDecimal {

        public static void main(String[] inArgs) {
          Amount a = new Amount("123", 2);
          System.out.println(a);
          System.out.println(a.doubleValue());
        }

        /**
         * Class to handle if an Amount has zero or two decimals.
         */
        public static class Amount extends BigDecimal {

          public Amount(String inAmount, int inScale) {
            super(new BigInteger(inAmount), inScale);
          }

          @Override
          public String toString() {
            return "Amount [amount=" + toPlainString() + "]";
          }
        }
      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Do not override toString.

            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: