2017-05-07 38 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

相關問題