How to format a number depending upon locale
I have an input box and my webpage supports English and German.
In the text box the user should enter only integer.
So how can I format the number from let say the user input 1,2 (in German) and then I want to ch开发者_如何学Ceck whether it's a valid integer but before doing that I need to convert it back to 1.2. How can i do this..?
Use the JDK's support for Locales:
public static void main(String[] args) throws Exception {
String str = "1,2";
Number number = DecimalFormat.getInstance(Locale.GERMAN).parse(str);
System.out.println(number);
}
Prints:
1.2
The answer is in the question (or at least in its tags). Use a NumberFormat
to parse the entered string, and if there is no ParseException
, the string is a valid integer.
To be completely true, NumberFormat
will happily parse 1,2ABC
to 1.2
. To avoid this, you can use the parse method taking a ParsePosition
as argument, and check that the position after the parsing is at the end of the string.
精彩评论