Best way to parseDouble with comma as decimal separator?
Because of the comma used as the decimal separator, this code throws a NumberFormatException
:
String p="1,234";
Double d=Double.valueOf(p);
System.out.println(d);
Is there a better way to parse "1,234"
to get 1.234
than: p = p.replaceAll(",",".");
?
Use java.text.NumberFormat:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();
Updated:
To support multi-language apps use:
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
You can use this (the French locale has ,
for decimal separator)
NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
nf.parse(p);
Or you can use java.text.DecimalFormat
and set the appropriate symbols:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
df.parse(p);