3

I'm having problems with users that have their locale settings set to non US countries getting errors when converting doubles to and from strings. So far I believe I have the correct way to convert the strings to doubles:

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

That is taking the input from an EditText box and converting it to a double. However I'm having problems converting doubles back to strings for to populate other EditText boxes. Here is the code I'm using that users are reporting crashes:

public String doubleToString(double d, String pattern){

        DecimalFormat df =(DecimalFormat) NumberFormat.getInstance(Locale.getDefault());
        df.applyLocalizedPattern(pattern);

        return df.format(d);
    }

I use the pattern string based on the amount of decimal places the edit text box has, for example "#0.00"

I can't figure out what's causing the crashes, and I can't even test it myself because I don't have those locales on my devices.

Any help would be greatly appreciated!

Matt
  • 2,650
  • 4
  • 36
  • 46
  • I don't have an answer to your question, but you can test this using other locales by setting the language/locale of an Android Emulator and running your app. – hooked82 Mar 04 '12 at 19:13

1 Answers1

2

You can use Locale.US instead of Locale.getDefault. Your string representations of doubles obviously aren't intended for direct interfacing with humans, and therefore the current locale should definitely not affect their interpretation.

Jirka Hanika
  • 13,301
  • 3
  • 46
  • 75