Andrei Stalbe
Andrei Stalbe

Reputation: 1531

Java convert a negative/positive string number into negative/pozitive double

Does anyone know how to convert the string value type -4,5 or 5,4 into a double -4.5 or 5.4?

Upvotes: 1

Views: 7665

Answers (2)

Pramod Kumar
Pramod Kumar

Reputation: 8014

First replace , with . and then use following function -

 Double.valueOf("-4.5");

and

Double.valueOf("5.4");

Upvotes: -1

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

Just use Double.parseDouble(Locale, String); Woops, I was confused...

You should use java.text.NumberFormat

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("-4,5");
double d = number.doubleValue();

For example, in Belgium or France we use a , as decimal separator. That is why it works.

Upvotes: 9

Related Questions