145

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?

demongolem
  • 9,474
  • 36
  • 90
  • 105
My Head Hurts
  • 37,315
  • 16
  • 75
  • 117

4 Answers4

241
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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
maerics
  • 151,642
  • 46
  • 269
  • 291
181

Use %03d in the format specifier for the integer. The 0 means that the number will be zero-filled if it is less than three (in this case) digits.

See the Formatter docs for other modifiers.

Mat
  • 202,337
  • 40
  • 393
  • 406
13

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

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

As StringUtils.leftPad() is faster than String.format()

Anil Bharadia
  • 2,760
  • 6
  • 34
  • 46
  • StringUtils.leftPad is another good choice and could be argued that it is more readable plus it allows you to pad with other characters. I have had a Google around but I cannot find anything that confirms it is faster - could you provide some evidence for that? – My Head Hurts Jul 09 '13 at 12:20
  • https://github.com/anilbharadia/JavaPerformanceTests/blob/master/PerformanceTests/src/org/rw/performance/StringUtilsVsStringFormat.java Run it with junit and check the time – Anil Bharadia Jul 10 '13 at 06:54
0

Instead of using String.format(**). it's good if you use DecimalFormat java API which builds for this type of purposes.Let me explain with code

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