Home >Java >javaTutorial >How to Efficiently Parse Doubles with Comma Decimal Separators in Java?

How to Efficiently Parse Doubles with Comma Decimal Separators in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 12:38:16776browse

How to Efficiently Parse Doubles with Comma Decimal Separators in Java?

Parsing Double with Comma Decimal Separator

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?

Better Parsing Method with java.text.NumberFormat

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().

Multi-Language Support

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn