Home >Java >javaTutorial >How to Parse Doubles with Comma as Decimal Separator in Java?

How to Parse Doubles with Comma as Decimal Separator in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-22 12:13:35750browse

How to Parse Doubles with Comma as Decimal Separator in Java?

Best way to parse using comma as the decimal separator

The implementation of Double.valueOf uses java.util.regex.Pattern to parse double value. The current pattern requires a dot character as decimal separator.

To resolve this, one approach is to replace the comma with a dot before parsing:

String p = "1,234";
p = p.replaceAll(",", ".");
Double d = Double.valueOf(p);
System.out.println(d);

However, there exists a more elegant way using java.text.NumberFormat:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

To support multi-language apps, the following code can be used:

NumberFormat format = NumberFormat.getInstance(Locale.getDefault());

The above is the detailed content of How to Parse Doubles with Comma as Decimal Separator 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