MarcF
MarcF

Reputation: 3299

What's the difference between formatting an integer as %d and %s ?

While both syntactically valid, are there any important underlying differences one should be aware of between:

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

vs:

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

where in both cases someIntValue is a int?

Upvotes: 14

Views: 6281

Answers (4)

jbx
jbx

Reputation: 22158

The %s will essentially call the object's toString() method. So most probably you will always get the integer as is.

The %d is informing the formatter it is actually an integer. There might be Locale specific formatting to abide to if for example it is using a Locale which has a different number system etc.

For a demo which illustrates the difference (%n generates OS dependant line separator):

Locale.setDefault(new Locale("th", "TH", "TH"));
System.out.printf("%s %n", 42); //output: 42
System.out.printf("%d %n", 42); //output: ๔๒

Upvotes: 6

MasterBlasterCoder
MasterBlasterCoder

Reputation: 52

No difference, Both are same because the integer will be taken as String! You can't use %d for String but you can use %s for int in String.format! you can even print the int with System.out.printf(), the integer will simply be parsed as String.

Upvotes: -2

Michael
Michael

Reputation: 44200

For formatter syntax see the documentation.

For %s:

If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().

Integer does not implement Formattable, so toString is called.

For %d:

The result is formatted as a decimal integer

In most cases the results are the same. However, %d is also subject to Locale. In Hindi, for example, 100000 will be formatted to १००००० (Devanagari numerals)

You can run this short code snippet to see locales with a "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);
}

Upvotes: 12

GiorgosDev
GiorgosDev

Reputation: 1767

In your case there's no difference, but in general it makes sens to use %s in case if you are not sure about type of value formatted.

Upvotes: 1

Related Questions