Skip to content
Advertisement

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(",",".");?

Advertisement

Answer

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());
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement