Java – what’s the difference between formatting integers as% D and% s?

Although both are grammatically valid, the following important potential differences should be noted:

String result = String.format("Here is a number - %s",someIntValue);

VS:

String result = String.format("Here is a number - %d",someIntValue);

In both cases, someintvalue is int?

Solution

For formatter syntax, see the documentation

For% s:

Integer does not implement formattable, so toString. Is called

For% d:

In most cases, the results are the same However,% d is also restricted by locale For example, in Hindi, 100000 will be formatted as 100000 (Devanagari numerals)

You can run this short snippet to view locales with non-standard output:

for (Locale locale : Locale.getAvailableLocales())
{
    String format = String.format(locale,"%d",100_000);

    if (!format.equals("100000")) System.out.println(locale + " " + format);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>