Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 697
Cute Shark Avatar asked Sep 29 '18 08:09

Cute Shark


2 Answers

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);
like image 96
xingbin Avatar answered Sep 22 '22 14:09

xingbin


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!

like image 36
Lê Đình Bảo Tín Avatar answered Sep 22 '22 14:09

Lê Đình Bảo Tín