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?
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);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With