为什么我使用 String.format 方法时没有添加逗号?

Why aren't commas added when I use String.format method?

public class TestFormats {
    public static void main(String[] args) {
        String str1 = String.format("%,d", 100000000);
        System.out.println(str1);
    }
}

我正在尝试使用带有给定参数的方法通过逗号分隔数字的数字,但由于某种原因,逗号没有添加到数字中,唯一改变的是出现了空格。

我怎样才能完成这项工作?为什么不工作,出了什么问题?

我觉得你的代码不错:

jshell>String str1 = String.format("%,d", 100000000);
...> 
str1 ==> "100,000,000"

可能您正在执行另一个文件(copy/pasted 并且缓冲区显示错误的文件,我经常遇到这种情况)

很有可能,您的系统区域设置未设置为 ENGLISH。使用 Locale.ENGLISH 如下图:

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

输出:

100,000,000

是因为你的Location。将 Locale 对象作为参数添加到 String.format() 函数

    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,100,100
            
            // 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
        }
    }