使用 Java 字符串格式设置整数的格式

我想知道是否有可能使用 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个空格。有没有可能在这个数字前面加上零呢?

320292 次浏览

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

有关其他修饰符,请参见 Formatter文档。

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

如果您正在使用名为 apache commons-lang 的第三方库,以下解决方案可能非常有用:

使用阿帕奇 Commons-langStringUtils类:

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

因为 StringUtils.leftPad()String.format()

而不是使用 String.format (* *)。如果你使用 DecimalFormat java API,它就是为这种目的而构建的。让我用密码解释一下

    String pattern = "000";
double value = 12; //can be 536 or any
DecimalFormat formatter = new DecimalFormat(pattern);
String formattedNumber = formatter.format(value);
System.out.println("Number:" + value + ", Pattern:" +
pattern + ", Formatted Number:" +
formattedNumber);