String.format 中的 %s 表示数字
如果不需要额外的格式,在格式化数字时是否有任何理由不使用 %s
作为格式说明符?
例如,
int answer = 42;
String text = String.format("The answer is %s", answer);
而不是更常见的:
int answer = 42;
String text = String.format("The answer is %d", answer);
我问的原因是我想对源代码进行一些自动更改,并且必须弄清楚 answer
的类型是否为 < code>int 或 String
或其他
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我预计在千位分隔符和其他特定于区域设置的选项方面存在潜在差异。第一种方法只是调用
Integer.toString
(它不区分区域设置),因为Integer
没有实现Formattable
。第二个是使用潜在的区域敏感整数格式 - 它可以插入数千个分隔符,甚至可能使用不同的数字集等。更仔细地查看文档,看起来分组分隔符不会'不能在没有特定格式标志的情况下应用,但是:
示例:
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) becauseInteger
doesn't implementFormattable
. 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:
Sample where it makes a difference: