java - %s in String.format 用于数字

标签 java printf

如果不需要额外的格式化,在格式化数字时是否有任何理由不使用 %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 的类型是否为 int< 会很不方便String 或其他东西

最佳答案

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

更仔细地查看文档,如果没有特定的格式标志,似乎不会应用分组分隔符,但是:

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.

发挥作用的示例:

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

关于java - %s in String.format 用于数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7872204/

相关文章:

c - 如何打印特定单词之前的所有内容以及特定单词之后的所有内容?

c - 程序在NetBeans中运行时无法输入数据

java - 如何在 android 中通过清理处理全局状态

Java 和开关盒

c - fork 中的 printf 错误

c - 我无法写入文件

c - 在循环中使用 printf 然后 scanf

Java,通过输入/输出流发送数据

java - 将jpa存储库添加到spring时出错

java - Android - 无法调整 AlertDialog 的大小