我可以使用什么 API 将 int
格式化为 2 位长?
例如在这个循环中
for (int i = 0; i < 100; i++) {
System.out.println("i is " + i);
}
我可以使用什么来确保 i
被打印出来,例如 01
、02
、10
、55
等(假设范围为 01-99 )
最佳答案
你可以这样做
System.out.printf("i is %02d%n", i);
查看 Formatter
的文档详情。相关部分是:
- The format specifiers for general, character, and numeric types have the following syntax:
%[argument_index$][flags][width][.precision]conversion
(在这种特殊情况下,0
作为标志,2
作为宽度,d
作为转换。)
Conversion
'd'
integral The result is formatted as a decimal integerFlags
'0'
The result will be zero-padded
这种格式化语法也可以用在其他一些地方,例如:
String str = String.format("i is %02d", i);
https://stackoverflow.com/questions/3975976/