Reputation:
public class TestFormats {
public static void main(String[] args) {
String str1 = String.format("%,d", 100000000);
System.out.println(str1);
}
}
I'm trying to separate digits of the number by commas using the method with the given parameters but, for some reason, commas aren't being added to the number, the only thing that's changed is that whitespaces emerged.
How can I make this work? Why isn't working, what's wrong?
Upvotes: 1
Views: 306
Reputation: 254
It is because of your Location
. Add the Locale
object as an argument to the String.format()
function
import java.util.Locale;
public class TestFormats {
public static void main(String[] args) {
// Uses commas
Locale localeEn = new Locale.Builder().setLanguage("en").build();
String str1 = String.format(localeEn, "%,d", 100_000_000);
System.out.println(str1); //output: 100,000,000
// Uses dots
Locale localeDe = new Locale.Builder().setLanguage("de").build();
String str2 = String.format(localeDe, "%,d", 100_000_000);
System.out.println(str2); //output: 100.000.000
// Uses spaces
Locale localeRu = new Locale.Builder().setLanguage("ru").build();
String str3 = String.format(localeRu, "%,d", 100_000_000);
System.out.println(str3); //output: 100 000 000
}
}
Upvotes: 3
Reputation: 79085
Most likely, your system Locale is not set to ENGLISH
. Use Locale.ENGLISH
as shown below:
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String str1 = String.format(Locale.ENGLISH, "%,d", 100000000);
System.out.println(str1);
}
}
Output:
100,000,000
Upvotes: 0
Reputation: 199225
Your code looks good to me:
jshell>String str1 = String.format("%,d", 100000000);
...>
str1 ==> "100,000,000"
Probably you're executing a different file (copy/pasted and buffer is showing the wrong file, happens to me all the time)
Upvotes: 0