How to Handle Comma as Decimal Separator in Double Parsing
The use of a comma as a decimal separator can lead to errors when using the standard Double.valueOf() method. Consider the following code:
String p = "1,234"; Double d = Double.valueOf(p); System.out.println(d);
This code will throw a NumberFormatException due to the presence of the comma. To handle this issue, one might consider using the p = p.replaceAll(",", ".") replacement technique. However, there is a more efficient and localized approach using the java.text.NumberFormat class.
Solution Using NumberFormat
The NumberFormat class allows for the parsing of numbers according to specific locale settings, including the handling of different decimal separators. Here's how to use it to parse a double with a comma separator:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE); Number number = format.parse("1,234"); double d = number.doubleValue();
In this code, NumberFormat.getInstance(Locale.FRANCE) creates an instance of the NumberFormat class with the French locale, where the comma is commonly used as a decimal separator. The format.parse() method then parses the string into a Number object, which can be converted to a double using the doubleValue() method.
Multi-Language Support
For multi-language applications, the Locale.getDefault() method can be used to obtain the default locale of the user's system:
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
This approach allows the code to adapt to the user's preferred locale and handle decimal separators accordingly.
The above is the detailed content of How to Correctly Parse Doubles with Comma as Decimal Separator in Java?. For more information, please follow other related articles on the PHP Chinese website!