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