Locale independent String to double

2019-02-24 19:23发布

问题:

In my app, I have edit text boxes where the user enters a decimal value that the app uses to run a calculation.

Some users in other locales are reporting problems when entering the numbers, like entering a value and a different one appearing. I have tried to fix this by getting the value from the editText with this method:

public double stringToDouble(String s){
        if (nf == null){
            nf = NumberFormat.getInstance(Locale.US);
        }
        try {
            return nf.parse(s).doubleValue();
        } catch (ParseException e) {
            e.printStackTrace();
            return 0.0;
        }
    }

and

val = stringToDouble(et.getText().toString());

But apparently that still isn't working for some people.

One user in Slovenia reported that it works fine if

  • settings; Language & keyboard :
  • Select language : set to English(Slovenia)
  • Touch input: set only to English and whatever language(my case Slovenia)
  • Bilingual prediction: OFF
  • Text prediction: OFF

What is the correct way to go about fetching the double values? Thanks

回答1:

From the looks of it, the correct way to do it is:

public double stringToDouble(String s){
        if (nf == null){
            nf = NumberFormat.getInstance(Locale.getDefault());
        }
        try {
            return nf.parse(s).doubleValue();
        } catch (ParseException e) {
            e.printStackTrace();
            return 0.0;
        }
    }

So far that seems to be working for me.