Best way to parse using comma as the decimal separator
The implementation of Double.valueOf uses java.util.regex.Pattern to parse double value. The current pattern requires a dot character as decimal separator.
To resolve this, one approach is to replace the comma with a dot before parsing:
String p = "1,234"; p = p.replaceAll(",", "."); Double d = Double.valueOf(p); System.out.println(d);
However, there exists a more elegant way using java.text.NumberFormat:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE); Number number = format.parse("1,234"); double d = number.doubleValue();
To support multi-language apps, the following code can be used:
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
The above is the detailed content of How to Parse Doubles with Comma as Decimal Separator in Java?. For more information, please follow other related articles on the PHP Chinese website!