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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-08 11:30:13452browse

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

Parsing Double with Comma as Decimal Separator: A Comprehensive Solution

When working with data that uses comma (,) as the decimal separator, parsing it into a double using Double.valueOf() can result in a NumberFormatException. This is because Double.valueOf() expects a period (.) as the decimal separator.

One solution is to replace the comma with a period using String.replaceAll(), as shown in the question. However, there is a more robust and locale-aware approach using java.text.NumberFormat.

Leveraging NumberFormat for Locale-Specific Parsing

NumberFormat provides methods to parse and format numbers according to the specified locale. To parse a string with a comma as the decimal separator, use the following steps:

  1. Create a NumberFormat instance using NumberFormat.getInstance(Locale.FRANCE) or NumberFormat.getInstance(Locale.getDefault()) to support multi-language apps.
  2. Call format.parse(String) to parse the string into a Number object.
  3. Convert the Number object to a double using number.doubleValue().

Here's the code demonstrating this approach:

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

System.out.println(d); // Prints 1.234

By using NumberFormat, you can parse double values with commas as decimal separators in a locale-specific manner, ensuring accurate results even in globalized applications.

The above is the detailed content of How to Robustly 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