Android 货币 - java.lang.NumberFormatException:对于输入字符串:“099”

Android Currency - java.lang.NumberFormatException: For input string: "099 "

java.lang.NumberFormatException: For input string: "099 "

这是我在 运行 this code 从另一个 SO 答案将 EditText 格式化为货币(逗号后的两个数字)时遇到的错误。

我会在这里重新发布我的代码:

price.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    String current = Double.toString(sub.getPrice());

    @Override
    public void afterTextChanged(Editable s) {
        if(!s.toString().equals("")){
            price.removeTextChangedListener(this);

            String replaceable = String.format("[%s,.]", NumberFormat.getCurrencyInstance(locale).getCurrency().getSymbol());

            String cleanString = s.toString().replaceAll(replaceable, "");

            double parsed = Double.parseDouble(cleanString);
            String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));

            current = formatted;
            price.setText(formatted);
            price.setSelection(formatted.length());

            price.addTextChangedListener(this);
        }
    }
});

price 只是一个 EditText.

到目前为止我尝试了什么:

我尝试强制货币为美元 ($) 而不是基于 locale 并且错误没有出现,而如果我使用欧元(基于区域设置)我得到错误。

我还注意到,将货币从美元转换为欧元时,符号从 ,00 变为 9,00 €。我怀疑数字和 € 之间的 space 导致 NumberFormatException 但我不知道如何解决它。

“9,00 €”中的 space 确实是问题所在。

现在你有两个选择:

  • 将白色space添加到可替换字符中以将其删除,即我们包括\s:

    String replaceable = String.format("[%s,.\s]", NumberFormat.getCurrencyInstance(locale).getCurrency().getSymbol());
    
  • 或 trim space 在尝试将其解析为双精度数之前:

    cleanString = cleanString.trim();
    double parsed = Double.parseDouble(cleanString);