问题

我想知道是否有可能使用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" ) );
}

不幸的是,这在数字前面有3个空格。相反,可以在数字前面加上零吗?


#1 热门回答(172 赞)

String.format("%03d", 1); // => "001"
//              │││   └── print the number one
//              ││└────── ... as a decimal integer
//              │└─────── ... minimum of 3 characters wide
//              └──────── ... pad with zeroes instead of spaces

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


#2 热门回答(149 赞)

在整数的格式说明符中使用%03d。如果它小于三(在这种情况下)数字,则该数字将为零填充.0

有关其他修饰符,请参阅Formatterdocs。


#3 热门回答(8 赞)

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

使用apachecommons-langStringUtils类:

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

AsStringUtils.leftPad()String.format()


原文链接