-1

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

This is the error I'm getting when I run this code from another SO answer that formats an EditText into currency (two numbers after comma).

I will repost my code here:

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 is simply an EditText.

What I tried so far:

I tried forcing the currency to be USD ($) instead of being based on locale and the error doesn't show up, While if I use EURO (based on locale) I get the error.

Also what I noticed that switching the currency from USD to EUR the symbol changes from something like $9,00 to 9,00 €. I suspect that the space between the numbers and the € causes the NumberFormatException but I have no clue on how to fix it.

Community
  • 1
  • 1
Daniele
  • 4,163
  • 7
  • 44
  • 95

1 Answers1

1

The space in "9,00 €" is indeed causing the problem.

Now you have two options:

  • Add the whitespace to the replaceable characters to remove it, i.e. we include \s:

    String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance(locale).getCurrency().getSymbol());
    
  • Or trim the space before trying to parse it as a double:

    cleanString = cleanString.trim();
    double parsed = Double.parseDouble(cleanString);
    
Floern
  • 33,559
  • 24
  • 104
  • 119