Cute Shark
Cute Shark

Reputation: 87

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

Upvotes: 6

Views: 432

Answers (2)

You can read about the format in Java in the link: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

For your problem, you can fix:

public static void main(String[] args) {

   String s = "1000000000";

   System.out.format("%,"+s.length()+"d%n", Long.parseLong(s));

}

Hope to helpfull!

Upvotes: 1

xingbin
xingbin

Reputation: 28279

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);

Upvotes: 4

Related Questions