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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3975976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:14:10  来源:igfitidea点击:

Which API can I use to format an int to 2 digits?

javaformattingint

提问by Jimmy

What API can I use to format an intto be 2 digits long?

我可以使用什么 API 将 an 格式化int为 2 位长?

For example, in this loop

例如,在这个循环中

for (int i = 0; i < 100; i++) {
   System.out.println("i is " + i);
}

What can I use to make sure iis printed out like 01, 02, 10, 55etc (assuming a range of 01-99 )

我可以使用,以确保i打印出像01021055等(假设范围01-99)

回答by aioobe

You could simply do

你可以简单地做

System.out.printf("i is %02d%n", i);

Have a look at the documentation for Formatterfor details. Relevant parts are:

Formatter有关详细信息,请查看文档。相关部分是:

  • The format specifiers for general, character, and numeric types have the following syntax:

        %[argument_index$][flags][width][.precision]conversion
  • 一般、字符和数字类型的格式说明符具有以下语法:

        %[argument_index$][flags][width][.precision]conversion

(In this particular case, you have 0as flag, 2as width, and das conversion.)

(在这种特殊情况下,您有0作为标志、2作为宽度和d作为转换。)

Conversion
'd'   integral      The result is formatted as a decimal integer

Flags
'0'                    The result will be zero-padded

转换
'd'   积分 结果格式为十进制整数

Flags
'0'                    结果将被零填充



This formatting syntax can be used in a few other places as well, for instance like this:

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

String str = String.format("i is %02d", i);

回答by medopal

Stringclass actually do formatting.

String类实际上是做格式化的。

For your case, try:

对于您的情况,请尝试:

String.format("%02d",i)

String.format("%02d",i)

回答by EMMERICH

You can use the DecimalFormatobject.

您可以使用DecimalFormat对象。

DecimalFormat formatter = new DecimalFormat("#00.###");
int test = 1;

System.out.println(formatter.format(test));

Will print "01".

将打印“01”。