ingelabs / classpath

GNU Classpath, Essential Libraries for Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

ingebot opened this issue · comments

Note: this issue was migrated automatically using bugzilla2github

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

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

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();
  }