Search code examples
javastringformatting

Why aren't commas added when I use String.format method?


public class TestFormats {
    public static void main(String[] args) {
        String str1 = String.format("%,d", 100000000);
        System.out.println(str1);
    }
}

I'm trying to separate digits of the number by commas using the method with the given parameters but, for some reason, commas aren't being added to the number, the only thing that's changed is that whitespaces emerged.

How can I make this work? Why isn't working, what's wrong?


Solution

  • Most likely, your system Locale is not set to ENGLISH. Use Locale.ENGLISH as shown below:

    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            String str1 = String.format(Locale.ENGLISH, "%,d", 100000000);
            System.out.println(str1);
        }
    }
    

    Output:

    100,000,000