Home >Java >javaTutorial >How to Safely Parse Doubles with Comma as Decimal Separator in Java?
How to Effectively Parse Double with Comma as Decimal Separator
Problem:
String values representing decimal numbers with commas as separators, like "1,234", can cause NumberFormatException when parsed using Double.valueOf().
Proposed Solution:
Replacing commas with periods using p = p.replaceAll(",", ".") is a valid approach, but there's a more robust method.
Java's NumberFormat for Decimal Parsing:
To handle decimals with locale-specific separators, Java provides NumberFormat. Consider the following code:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE); Number number = format.parse("1,234"); double d = number.doubleValue();
Update for Multi-Language Applications:
In multilingual applications, locale-specific decimal separators are important. To support this, use NumberFormat.getInstance(Locale.getDefault()) to get the current locale's format.
Advantages of NumberFormat:
The above is the detailed content of How to Safely Parse Doubles with Comma as Decimal Separator in Java?. For more information, please follow other related articles on the PHP Chinese website!