Michael Hegner
Michael Hegner

Reputation: 5823

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.

Upvotes: 1

Views: 283

Answers (2)

user6073886
user6073886

Reputation:

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

Upvotes: 1

Strahinja
Strahinja

Reputation: 460

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.

Upvotes: 0

Related Questions