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

Insufficient BigDecimal and BigInteger Defaulting Behaviour

XMLWordPrintable

      A DESCRIPTION OF THE REQUEST :
      BigDecimal and BigInteger arithmetic does not default to decimal, non-floating point arithmetic mode.

      BigDecimal a = new BigDecimal(0.1);
           
      BigDecimal b = new BigDecimal(0.1);
           
      BigDecimal x = a.multiply(b);
           
      out.println(x.stripTrailingZeros().toPlainString());


      JUSTIFICATION :
      In order for this to produce the anticipated behaviour,
      there must be a MathContext object submitted, scale
      values set for a and b (or rounding performed on the multiply call),
      none of which should be necessary in this example.


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Should print an answer of

      0.01

      with no further configuration.
      ACTUAL -
      Instead prints out a floating point default result of

      0.01000000000000000111022302462515657123851077828659396139564708135883709660962637144621112383902072906494140625

      ---------- BEGIN SOURCE ----------
      import java.math.RoundingMode;
      import java.math.MathContext;
      import java.math.BigDecimal;
      import static java.lang.System.out;

      public class ArbitraryNumbers
      {
      public static void main(String ... args)
      {
      BigDecimal a = new BigDecimal(0.1);
           
      BigDecimal b = new BigDecimal(0.1);
           
      BigDecimal x = a.multiply(b);
           
      out.println(x.stripTrailingZeros().toPlainString());
      }
      }
      ---------- END SOURCE ----------

            darcy Joe Darcy
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: