6

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

4
  • 2
    It works fine in my side
    – flyingfox
    Commented Sep 29, 2018 at 8:29
  • 1
    Your output is different because of your locale. If you put Locale.setDefault(Locale.US); before the call to format, the output would match that of the book. Seems that your OS has french-like number format rules.
    – ernest_k
    Commented Sep 29, 2018 at 8:34
  • @ernest_k thank you so much! this answers my question perfectly!
    – Cute Shark
    Commented Sep 29, 2018 at 8:38
  • 3
    The book should at least have mentioned that String.format is locale-sensitive and that the actual output may differ.
    – MC Emperor
    Commented Sep 29, 2018 at 8:52

2 Answers 2

4

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);
3
  • 2
    but what about the example? is it completely wrong then? why doesn't it work?
    – Cute Shark
    Commented Sep 29, 2018 at 8:35
  • @CuteShark See the comment of ernest_k.
    – xingbin
    Commented Sep 29, 2018 at 8:39
  • Yes, I've already checked it and it works. So now I have no questions left about this issue :)
    – Cute Shark
    Commented Sep 29, 2018 at 8:41
1

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.