letsCode
letsCode

Reputation: 3046

Convert large number with comma/decimal to Double

My server is returning a string like 2,100.00.

I get a NumberFormatException when I try to convert this String into a double.

Double.valueOf("2,100.00");

Do I have to remove the decimal/comma, convert, and add the decimal back in?

Upvotes: 1

Views: 102

Answers (2)

Anuradha
Anuradha

Reputation: 580

Yes you have to remove the comma. This solution would be more simple:

String str = "2,100.00";
Double.valueOf(str.replaceAll(",", ""));

Upvotes: 0

MadaManu
MadaManu

Reputation: 886

You could set a custom separator in a decimal format

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
Number number = df.parse(str);

Then you can use the number. To convert it to double you can do number.doubleValue()

Upvotes: 6

Related Questions