Search code examples
javaandroidbigdecimaldecimalformat

StringIndexOutOfBoundsException after formatting BigDecimal


We are getting the following error while attempting to retrieve the dollar amount without the cents:

Caused by java.lang.StringIndexOutOfBoundsException length=6; regionStart=0; regionLength=-1

Here is the code:

public static String findDollarAmount(@Nullable BigDecimal fullAmount) {
    if (fullAmount == null || fullAmount.compareTo(BigDecimal.ZERO) == 0) {
        return "0";
    }

    DecimalFormat df = new DecimalFormat("#,##0.00;-#,##0.00");

    //This value is returned as some string value that doesn't contain a '.'
    String amountStr = df.format(fullAmount);

    //The crash happens on this line
    return amountStr.substring(0, amountStr.indexOf('.'));
}

We are not able to print out the values in production and we aren't able to recreated this scenario during testing. Any help would be greatly appreciated.


Solution

  • It can be your application Locale.
    If the application's Locale has as its currency representation the decimal separator "," as in PT-BR (R$ 1.000,00) will cause exception when performing.
    Another hand, sample , the Locale being set to US Locale.setDefault(Locale.US) will have decimal separator "." like $1,000.00 and no problem.