java – 可以使用哪个API将int格式化为2位数?

前端之家收集整理的这篇文章主要介绍了java – 可以使用哪个API将int格式化为2位数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以使用什么API将int格式化为2位数字?

例如,在这个循环中

for (int i = 0; i < 100; i++) {
   System.out.println("i is " + 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' integralThe result is formatted as a decimal integer

Flags
'0' The result will be zero-padded

这种格式化语法也可以在其他几个地方使用,例如:

String str = String.format("i is %02d",i);
原文链接:https://www.f2er.com/java/122463.html

猜你在找的Java相关文章