Format an Integer using Java String Format

My Head Hurts picture My Head Hurts · May 17, 2011 · Viewed 291k times · Source

I am wondering if it is possible, using the String.format method in Java, to give an integer preceding zeros?

For example:

1 would become 001
2 would become 002
...
11 would become 011
12 would become 012
...
526 would remain as 526
...etc

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" ) );
}

Unfortunately, this precedes the number with 3 empty spaces. Is it possible to precede the number with zeros instead?

Answer

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

See java.util.Formatter for more information.