"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Java efficiently parses comma-separated double-precision number method

Java efficiently parses comma-separated double-precision number method

Posted on 2025-04-13
Browse:828

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3