Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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?

like image 748
MarcF Avatar asked Jun 14 '18 09:06

MarcF


People also ask

What is %d and %s in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))

What is %d and %s in Java?

%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.

What is %s in print Python?

%s acts as a placeholder for the real value. You place the real value after the % operator. This method is often referred to as the "older" way because Python 3 introduced str. format() and formatted string literals (f-strings).

What does %s mean in a Python format string?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.


1 Answers

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);
}
like image 172
Michael Avatar answered Sep 19 '22 00:09

Michael