Bug 90755 - BigDecimal.stripTrailingZero throws exception if value is zero
Summary: BigDecimal.stripTrailingZero throws exception if value is zero
Alias: None
Product: classpath
Classification: Unclassified
Component: classpath (show other bugs)
Version: 0.99
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
Depends on:
Reported: 2019-06-05 09:55 UTC by Guillermo Rodriguez
Modified: 2019-06-05 09:56 UTC (History)
0 users

See Also:
Known to work:
Known to fail:
Last reconfirmed:


Note You need to log in before you can comment on or make changes to this bug.
Description Guillermo Rodriguez 2019-06-05 09:55:20 UTC
Here's a simple test case:

    BigDecimal bd1 = new BigDecimal("0.001");
    bd1 = bd1.setScale(2, BigDecimal.ROUND_HALF_UP);
    bd1 = bd1.stripTrailingZeros();

This results in:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
   at java.lang.String.charAt(String.java:692)
   at java.math.BigDecimal.stripTrailingZeros(BigDecimal.java:1340)

Here's the code that throws the exception:

  public BigDecimal stripTrailingZeros()
    String intValStr = intVal.toString();
    int newScale = scale;
    int pointer = intValStr.length() - 1;
    // This loop adjusts pointer which will be used to give us the substring
    // of intValStr to use in our new BigDecimal, and also accordingly
    // adjusts the scale of our new BigDecimal.
    while (intValStr.charAt(pointer) == '0')
        pointer --;
        newScale --;

The above loop will happily walk beyond the end of the string if all digits are '0'.
Comment 1 Guillermo Rodriguez 2019-06-05 09:56:44 UTC
Here's a simple fix:

  public BigDecimal stripTrailingZeros()
+   if (intVal.signum() == 0) return ZERO;

    String intValStr = intVal.toString();