Home >Java >javaTutorial >How to Efficiently Parse Doubles with Comma Decimal Separators in Java?
In Java, using the default NumberFormat can lead to errors when parsing strings with commas as decimal separators. Consider the following code:
String p = "1,234"; Double d = Double.valueOf(p); System.out.println(d);
This code will throw a NumberFormatException. To overcome this issue, a convenient solution would be to replace the comma with a period using p.replaceAll(",", "."). However, is there a more efficient way?
The java.text.NumberFormat class offers a sophisticated solution. It allows you to specify the locale-specific formatting rules, ensuring that the decimal separator is recognized correctly. Here's how to use NumberFormat:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE); Number number = format.parse("1,234"); double d = number.doubleValue();
In this code, we instantiate a NumberFormat for the French locale, where the comma is used as a decimal separator. The parse() method converts the string to a Number object, which we then convert to a double using doubleValue().
To support multi-language applications, use the following code:
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
This will create a NumberFormat for the default locale, which is the locale of the current user's operating system.
The above is the detailed content of How to Efficiently Parse Doubles with Comma Decimal Separators in Java?. For more information, please follow other related articles on the PHP Chinese website!