String.format 中的 %s 表示数字

发布于 2024-12-11 09:55:49 字数 396 浏览 0 评论 0原文

如果不需要额外的格式,在格式化数字时是否有任何理由不使用 %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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南街九尾狐 2024-12-18 09:55:49

我预计在千位分隔符和其他特定于区域设置的选项方面存在潜在差异。第一种方法只是调用 Integer.toString (它不区分区域设置),因为 Integer 没有实现 Formattable。第二个是使用潜在的区域敏感整数格式 - 它可以插入数千个分隔符,甚至可能使用不同的数字集等。

更仔细地查看文档,看起来分组分隔符不会'不能在没有特定格式标志的情况下应用,但是:

号码定位算法

获得整数部分、小数部分和指数(根据数据类型而定)的数字后,将应用以下转换:

  • 字符串中的每个数字字符 d 都替换为相对于当前语言环境的零数字 z 计算的语言环境特定数字;即 d - '0' + z。

示例:

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);
  }
}

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);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文