简体   繁体   中英

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 check 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM