使用Javastring格式格式化整数
我想知道是否有可能使用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个空格。 是否有可能在数字前面加上零来代替?
 在格式说明符中使用%03d作为整数。  0表示如果数字小于3(在这种情况下)数字,则该数字将被填满。 
 请参阅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的第三方库,则以下解决scheme可能非常有用:
 使用apache commons-lang的 StringUtils类: 
 int i = 5; StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005" 
 由于StringUtils.leftPad()比String.format()更快