Search code examples
javanumber-formatting

How to insert commas into a number?


I've found such an example of using String.format() in a book:

package stringFormat;

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

According to the book the output should be: 1,000,000,000. But when I run the code I only get 1 000 000 000 without the commas. Why? how can I get it with commas?

output picture


Solution

  • Reproduce the problem with Locale.FRANCE:

    Locale.setDefault(Locale.FRANCE);
    
    String test = String.format("%, d", 1000000000);
    System.out.println(test); //  1 000 000 000
    

    You can avoid this with Locale.US:

    String test = String.format(Locale.US, "%, d", 1000000000);
    
    or
    
    Locale.setDefault(Locale.US);
    String test = String.format("%, d", 1000000000);