格式化 BigDecimal 后出现 StringIndexOutOfBoundsException

StringIndexOutOfBoundsException after formatting BigDecimal

我们在尝试检索不含美分的美元金额时遇到以下错误:

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

代码如下:

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

我们无法打印出生产中的值,也无法在测试期间重新创建此场景。任何帮助将不胜感激。

可能与关于 Java .substring 方法的这个事实有关:

The substring begins at the specified beginIndex and extends to the character at index endIndex – 1 Found here

基于此,您可能需要执行类似...

return amountStr.substring(0, amountStr.indexOf('.') - 1);

也许您的格式有误,在模拟中它似乎 return 类似于“10,00”,而您却试图找到一个点“.”。 通过在第二个 return 之前插入一个 System.out.println(amountStr); 来检查它,您将能够看到字符串的格式。 就像这样:

10,00

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 5

可以是你的应用Locale.
如果应用程序的区域设置将小数点分隔符“,”作为其货币表示,如 PT-BR (R$ 1.000,00) 中那样,将在执行时导致异常。
另一方面,示例,设置为 US Locale.setDefault(Locale.US) 的 Locale 将有小数点分隔符“.”就像 $1,000.00 没问题。