1

I am playing with NumberFormat, but somehow I cant get a e.g. "12.34" into a Number.

What I do:

NumberFormat nf = NumberFormat.getInstance();
try {
    return nf.parse(inputString);
} catch (ParseException e) {
    return null;
}

When I give it "34.45", 3445 comes out.

Michael Hegner
  • 5,555
  • 9
  • 38
  • 64
  • 4
    What locale is your system set to / what country are you from? NumberFormat.getInstance() will get the NumberFormat instance corresponding to your current locale. Since your name sounds german you should consider that dot is not the decimal sign in german number formats. Try to use `NumberFormat.getInstance(Locale.ROOT)` to ignore the JVMs default locale setting. – OH GOD SPIDERS Sep 22 '17 at 08:59
  • Hey Mr. Spider, thank you for your answer. If you write it as anwer, than I can accept it. :-) – Michael Hegner Sep 22 '17 at 09:31

2 Answers2

1
NumberFormat.getInstance();

Will get an Instance of NumberFormat for the current default FORMAT locale of the JVM the program is running in.

Not every locale format uses dot as a decimal sign. Guessing by your name you are probably having german as a default locale and therefor comma is used as the decimal sign while dot is interpreted as a simple (thousands) separator that is used to make numbers more human readable.

To get a NumberFormat instance that ignores the current default locale you can use:

NumberFormat.getInstance(Locale.ROOT);
OH GOD SPIDERS
  • 3,091
  • 2
  • 13
  • 16
0

Try using comma instead of dot. It depends of the system locale you're using. Somewhere decimal is written by dot, and somewhere is written by comma.
And check here how to convert a string to double using a specific locale.

Strahinja
  • 440
  • 9
  • 26