Reputation: 43157
Is there any reason not to use %s
for the format specifier when formatting numbers if no extra formatting is required?
e.g.
int answer = 42;
String text = String.format("The answer is %s", answer);
rather than the more usual:
int answer = 42;
String text = String.format("The answer is %d", answer);
The reason I'm asking is that I want to make some automated changes to source code, and it would be inconvenient to have to figure out whether the type of answer
is int
or String
or something else
Upvotes: 26
Views: 95672
Reputation: 1502166
I would expect there to be a potential difference in terms of thousands separators and other locale-specific options. The first approach is just going to call Integer.toString
(which is not locale-sensitive) because Integer
doesn't implement Formattable
. The second is going to use potentially locale-sensitive integer formatting - it could insert thousands separators, potentially even use a different set of digits etc.
Looking at the docs more carefully, it looks like grouping separators won't be applied without a specific formatting flag, but:
Number Localization Algorithm
After digits are obtained for the integer part, fractional part, and exponent (as appropriate for the data type), the following transformation is applied:
- Each digit character d in the string is replaced by a locale-specific digit computed relative to the current locale's zero digit z; that is d - '0' + z.
Sample where it makes a difference:
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Locale.setDefault(new Locale("hi", "IN"));
System.out.printf("String: %s; Number: %d\n", 1234, 1234);
}
}
Upvotes: 38