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

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

DDD
Release: 2024-12-12 22:07:16
Original
635 people have browsed it

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

How to Handle Comma as Decimal Separator in Double Parsing

The use of a comma as a decimal separator can lead to errors when using the standard Double.valueOf() method. Consider the following code:

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

This code will throw a NumberFormatException due to the presence of the comma. To handle this issue, one might consider using the p = p.replaceAll(",", ".") replacement technique. However, there is a more efficient and localized approach using the java.text.NumberFormat class.

Solution Using NumberFormat

The NumberFormat class allows for the parsing of numbers according to specific locale settings, including the handling of different decimal separators. Here's how to use it to parse a double with a comma separator:

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

In this code, NumberFormat.getInstance(Locale.FRANCE) creates an instance of the NumberFormat class with the French locale, where the comma is commonly used as a decimal separator. The format.parse() method then parses the string into a Number object, which can be converted to a double using the doubleValue() method.

Multi-Language Support

For multi-language applications, the Locale.getDefault() method can be used to obtain the default locale of the user's system:

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

This approach allows the code to adapt to the user's preferred locale and handle decimal separators accordingly.

The above is the detailed content of How to Correctly 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template