Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubles, commas and dots

I'm making an Android Java program which is taking double values from the user. If I run the program on the computer, it works great because of the locale of my computer, EN_UK. But when I run it on my mobile phone with FI_FI locale, it won't work. I know the reason: In UK, people use dot as decimal separator but here in Finland, the decimal separator is comma.

DecimalFormat df = new DecimalFormat("#.#");
Double returnValue = Double.valueOf(df.format(doubleNumber));

When I'm using comma, it says java.lang.NumberFormatException: Invalid double: "1234,5".

How can I make it work with them both, comma and dot?

like image 518
MikkoP Avatar asked May 14 '12 14:05

MikkoP


2 Answers

Use one of the other constructors of DecimalFormat:

new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US))

And then try and parse it using both separators.

like image 91
Jerome Avatar answered Sep 27 '22 17:09

Jerome


using DecimalFormatSymbols.getInstance() will produce the default locale's correct symbols, so you will get it right for any platform you run on.

DecimalFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance());
like image 32
danf Avatar answered Sep 27 '22 17:09

danf