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
Which API can I use to format an int to 2 digits?
提问by Jimmy
What API can I use to format an int
to 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 i
is printed out like 01
, 02
, 10
, 55
etc (assuming a range of 01-99 )
我可以使用,以确保i
打印出像01
,02
,10
,55
等(假设范围01-99)
回答by aioobe
You could simply do
你可以简单地做
System.out.printf("i is %02d%n", i);
Have a look at the documentation for Formatter
for 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 0
as flag, 2
as width, and d
as conversion.)
(在这种特殊情况下,您有0
作为标志、2
作为宽度和d
作为转换。)
Conversion
'd'
integral The result is formatted as a decimal integerFlags
'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
String
class 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”。