解析货币以加倍引发异常

Parsing currency to double raising exception

我有一个 "R.333,33" 的字符串,我正在尝试使用此方法将其解析为双精度值:

public static BigDecimal parse(final String amount, final Locale locale) throws ParseException {
        final NumberFormat format = NumberFormat.getCurrencyInstance(locale);
        if (format instanceof DecimalFormat) {
            ((DecimalFormat) format).setParseBigDecimal(true);
        }
        return (BigDecimal) format.parse(amount.replaceAll("[^\d.,]", ""));
    }

但我收到一个异常:

W/System.err: java.text.ParseException: Unparseable number: "3.333,33" (at offset 8)

我使用它的方式如下:

Ferramentas.parse(value.getText().toString(), Locale.FRANCE)

看看this question and answer

虽然它看起来像重复的,但如果您的输入是 "R$ 3.333,33",parse 方法就有效(注意货币符号和值之间的 space)。

要在货币符号和值之间插入一个space,您可以使用这样的方法:

public static String insertSpaceBetweenSymbolAndValue(String s)
{
    int index = 0;
    while (index < s.length() && !Character.isDigit(s.charAt(index)))
        index++;
    return (index != s.length()) ? s.substring(0, index) + " " + s.substring(index) : s;
}

我找到的唯一解决方案是在您的正则表达式中也替换 .

return (BigDecimal) format.parse(amount.replaceAll("[^\d,]",""));

我无法解析带有 . 的数以千计。

  • 如果保留 .,它会被解析为 3
  • 如果您将 . 替换为 ,,它会被解析为 3.333

如果有人对 . 有成千上万的解决方案,我真的很想听听。

你为什么不删除 'R$ ',然后解析你的替身?

String s = b.substring(3, b.length()); 
Double d = Double.valueOf(s);