ingelabs / classpath

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

BigDecimal.stripTrailingZero throws exception if value is zero #13

Closed ingebot closed 1 year ago

ingebot commented 5 years ago

Note: this issue was migrated automatically using bugzilla2github

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

ingebot commented 5 years ago

Comment author: @guillerodriguez

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'.

ingebot commented 5 years ago

Comment author: @guillerodriguez

Here's a simple fix:

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

    String intValStr = intVal.toString();
    [...]