使用Java字符串格式格式化整数

My *_*rts 122 java string-formatting number-formatting

我想知道是否有可能使用Java中的String.format方法给出一个前面的零整数?

例如:

1将成为001
2将成为002
...
11将成为011
12将成为012
...
526将保持为526
......等

目前我尝试了以下代码:

String imageName = "_%3d" + "_%s";

for( int i = 0; i < 1000; i++ ){
    System.out.println( String.format( imageName, i, "foo" ) );
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这在数字前面有3个空格.是否可以在数字前面加零?

mae*_*ics 199

String.format("%03d", 1)  // => "001"
//              ???   ??? print the number one
//              ????????? ... as a decimal integer
//              ????????? ... minimum of 3 characters wide
//              ????????? ... pad with zeroes instead of spaces
Run Code Online (Sandbox Code Playgroud)

有关java.util.Formatter更多信息,请参阅


Mat*_*Mat 169

使用%03d格式说明为整数.这0意味着如果数字少于三个(在这种情况下)数字,则该数字将为零.

请参阅Formatter其他修饰符的文档.


Ani*_*dia 10

如果您使用的是名为apache commons-lang的第三方库,则以下解决方案可能很有用:

使用StringUtilsapache commons-lang类:

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
Run Code Online (Sandbox Code Playgroud)

由于StringUtils.leftPad()比快String.format()