2017-05-07 50 views
-1

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,但我不知道如何解决它。

+0

修剪您的字符串,如果您希望它是有效的数字字符串。 –

+0

我真的不明白为什么它被拒绝... – Daniele

+0

可能重复[什么是NumberFormatException,我该如何解决它?](https://stackoverflow.com/questions/39849984/what-is- a-numberformatexception-and-how-can-i-fix-it) – xenteros

回答

1

“9,00€”的空间确实导致了问题。

现在你有两个选择:

  • 添加空格可置换的字符将其删除,即我们有\s

    String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance(locale).getCurrency().getSymbol()); 
    
  • 或者试图解析之前裁剪空间作为双精度:

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

'[%s,。\\s]'为我做了诡计,谢谢你的出色答案。 – Daniele

相关问题