虽然两者在语法上都是有效的,但是之间应该注意以下重要的潜在差异:
String result = String.format("Here is a number - %s", someIntValue);
VS:
String result = String.format("Here is a number - %d", someIntValue);
在两种情况下someIntValue都是int?
有关格式化程序语法,请参阅
the documentation.
对于%s:
If arg implements Formattable, then arg.formatTo is
invoked. Otherwise, the result is obtained by invoking arg.toString().
Integer不实现Formattable,因此调用toString.
对于%d:
The result is formatted as a decimal integer
在大多数情况下,结果是相同的.但是,%d也受Locale限制.例如,在印地语中,100000将格式化为100000(Devanagari numerals)
您可以运行此简短代码段以查看具有“非标准”输出的区域设置:
for (Locale locale : Locale.getAvailableLocales())
{
String format = String.format(locale, "%d", 100_000);
if (!format.equals("100000")) System.out.println(locale + " " + format);
}