使用Java字符串格式格式化整数 [英] Format an Integer using Java String Format
问题描述
我想知道是否有可能使用Java中的String.format方法给出一个前面的零整数?
I am wondering if it is possible, using the String.format method in Java, to give an integer preceding zeros?
例如:
1将成为001
2将成为002
...
11将成为011
12将成为012
...
526将保留为526 b
等等>
目前我尝试了以下代码:
At the moment I have tried the following code:
String imageName = "_%3d" + "_%s";
for( int i = 0; i < 1000; i++ ){
System.out.println( String.format( imageName, i, "foo" ) );
}
不幸的是,这在数字前面有3个空格。是否可以在数字前加上零?
Unfortunately, this precedes the number with 3 empty spaces. Is it possible to precede the number with zeros instead?
推荐答案
使用%03d
在整数的格式说明符中。 0
表示如果该数字少于三个(在本例中为)数字,则该数字将为零。
Use %03d
in the format specifier for the integer. The 0
means that the number will be zero-filled if it is less than three (in this case) digits.
请参阅 Formatter
其他修饰语的文档。
See the Formatter
docs for other modifiers.
这篇关于使用Java字符串格式格式化整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!