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?
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().
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.
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