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
?
%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))
%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.
%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).
%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.
For formatter syntax see the documentation.
For %s
:
If arg implements
Formattable
, thenarg.formatTo
is invoked. Otherwise, the result is obtained by invokingarg.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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With