How do I convert a String to Double in Java using a specific locale?

Solution 1:

Try java.text.NumberFormat. From the Javadocs:

To format a number for a different Locale, specify it in the call to getInstance.

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);

You can also use a NumberFormat to parse numbers:

myNumber = nf.parse(myString);

parse() returns a Number; so to get a double, you must call myNumber.doubleValue():

    double myNumber = nf.parse(myString).doubleValue();

Note that parse() will never return null, so this cannot cause a NullPointerException. Instead, parse throws a checked ParseException if it fails.

Edit: I originally said that there was another way to convert to double: cast the result to Double and use unboxing. I thought that since a general-purpose instance of NumberFormat was being used (per the Javadocs for getInstance), it would always return a Double. But DJClayworth points out that the Javadocs for parse(String, ParsePosition) (which is called by parse(String)) say that a Long is returned if possible. Therefore, casting the result to Double is unsafe and should not be tried!
Thanks, DJClayworth!

Solution 2:

NumberFormat is the way to go, but you should be aware of its peculiarities which crop up when your data is less than 100% correct.

I found the following usefull:

http://www.ibm.com/developerworks/java/library/j-numberformat/index.html

If your input can be trusted then you don't have to worry about it.

Solution 3:

Just learning java and programming. Had similar question. Found something like this in my textbook:

Scanner sc = new Scanner(string);
double number = sc.nextDouble();

The book says that a scanner automatically decodes what's in a String variabel and that the Scanner class automatically adapts to the language of the set Locale, system Locale being the default, but that's easy to set to something else.

I solved my problem this way. Maybe this could work for the above issue instead of parsing?

Addition: The reason I liked this method was the fact that when using swing dialouge boxes for input and then trying to convert the string to double with parse I got a NumberFormatException. It turned out that parse exclusively uses US-number formatting while Scanner can handle all formats. Scanner made the input work flawlessly even with the comma (,) decimal separator. Since the most voted up answer uses parse I really don't see how it would solve this particular problem. You would have to input your numbers in US format and then convert them to your locale format. That's rather inconvenient when ones numeric keybord is fitted with a comma.

Now you're all free to shred me to pieces ;)

Solution 4:

You use a NumberFormat. Here is one example, which I think looks correct.