Search code examples
javaparsingnumber-formatting

Convert a DoubleValue as String to Number using NumberFormat


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.


Solution

  • 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);