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
Release: 2024-12-22 12:13:35
Original
685 people have browsed it

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);
Copy after login

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();
Copy after login

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

NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template