ingelabs / classpath

GNU Classpath, Essential Libraries for Java
Other
8 stars 3 forks source link

BigDecimal.toPlainString() gives wrong result for negative integer values #12

Closed ingebot closed 1 year ago

ingebot commented 5 years ago

Note: this issue was migrated automatically using bugzilla2github

Original bug ID: BZ#90759 From: @guillerodriguez Reported version: 0.99

ingebot commented 5 years ago

Comment author: @guillerodriguez

BigDecimal.toPlainString() does not work as expected for negative integer values if the scale is also < 0.

Here's a test case:

    bd = new BigDecimal(-10);
    bd = bd.stripTrailingZeros();
    System.out.println("toString(): " + bd);
    System.out.println("toPlainString(): " + bd.toPlainString());

    BigDecimal bd = new BigDecimal(new BigInteger("-1", 10), -1);
    System.out.println("toString(): " + bd);
    System.out.println("toPlainString(): " + bd.toPlainString());

This prints:

toString(): -1.E+1
toPlainString(): -1  // -> should be -10
toString(): -1.E+1
toPlainString(): -1  // -> should be -10
ingebot commented 5 years ago

Comment author: @guillerodriguez

Here's a fix for this bug:

  public String toPlainString()
  {
    [...]
    else
      {
        // We must append zeros instead of using scientific notation.
        sb.append(bigStr);
+       int ndigits = bigStr.length() - (negative ? 1 : 0);
+       for (int i = ndigits; i < point; i++)
-       for (int i = bigStr.length(); i < point; i++)
          sb.append('0');
      }
    return sb.toString();
  }