Android Currency-java.lang.NumberFormatException:输入字符串的异常值为;099 &引用;
java.lang.NumberFormatException:用于输入字符串:“099” 这是我从另一个SO答案运行时遇到的错误,该答案将EditText格式化为货币(逗号后有两个数字) 我将在此处重新发布我的代码:Android Currency-java.lang.NumberFormatException:输入字符串的异常值为;099 &引用;,android,numberformatexception,currency-formatting,Android,Numberformatexception,Currency Formatting,java.lang.NumberFormatException:用于输入字符串:“099” 这是我从另一个SO答案运行时遇到的错误,该答案将EditText格式化为货币(逗号后有两个数字) 我将在此处重新发布我的代码: price.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int a
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
到目前为止我所尝试的:
我尝试强制货币为USD($),而不是基于locale
,但错误没有出现,而如果使用欧元(基于locale),则会出现错误
我还注意到,将货币从美元换成欧元时,符号从$9,00
变为9,00€
。我怀疑数字和欧元之间的空格导致了NumberFormatException
,但我不知道如何解决它。9,00欧元中的空格确实导致了问题
现在您有两个选择:
- 将空白添加到可替换字符以删除它,即我们包括
:\s
String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance(locale).getCurrency().getSymbol());
- 或者在尝试将其解析为双精度之前修剪空间:
cleanString = cleanString.trim(); double parsed = Double.parseDouble(cleanString);
[%s,.\\s]
帮了我的忙,谢谢您的回答。