Home >Java >javaTutorial >How to Robustly Parse Doubles with Comma as Decimal Separator in Java?
Parsing Double with Comma as Decimal Separator: A Comprehensive Solution
When working with data that uses comma (,) as the decimal separator, parsing it into a double using Double.valueOf() can result in a NumberFormatException. This is because Double.valueOf() expects a period (.) as the decimal separator.
One solution is to replace the comma with a period using String.replaceAll(), as shown in the question. However, there is a more robust and locale-aware approach using java.text.NumberFormat.
Leveraging NumberFormat for Locale-Specific Parsing
NumberFormat provides methods to parse and format numbers according to the specified locale. To parse a string with a comma as the decimal separator, use the following steps:
Here's the code demonstrating this approach:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE); Number number = format.parse("1,234"); double d = number.doubleValue(); System.out.println(d); // Prints 1.234
By using NumberFormat, you can parse double values with commas as decimal separators in a locale-specific manner, ensuring accurate results even in globalized applications.
The above is the detailed content of How to Robustly Parse Doubles with Comma as Decimal Separator in Java?. For more information, please follow other related articles on the PHP Chinese website!