Search code examples
javalocalenumber-formatting

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


Solution

  • 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