java.lang.NumberFormatException:对于输入字符串: “099”Android的货币 - java.lang.NumberFormatException:对于输入字符串: “099”
这是我得到的错误,当我从另一个SO答案运行this code,该答案将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
和错误显示不出来,虽然如果我使用EURO(基于locale)我得到错误。
另外我注意到,将货币从美元转换为欧元,符号从$9,00
变为9,00 €
。我怀疑数字和€之间的空格导致NumberFormatException
,但我不知道如何解决它。
修剪您的字符串,如果您希望它是有效的数字字符串。 –
我真的不明白为什么它被拒绝... – Daniele
可能重复[什么是NumberFormatException,我该如何解决它?](https://stackoverflow.com/questions/39849984/what-is- a-numberformatexception-and-how-can-i-fix-it) – xenteros