Convert 1 to 01

Presumably you mean to store the number in a String.

Since JDK1.5 there has been the String.format() method, which will let you do exactly what you want:

String s = String.format("%02d", someNumber);

One of the nice things about String.format() is that you can use it to build up more complex strings without resorting to lots of concatenation, resulting in much cleaner code.

String logMessage = String.format("Error processing record %d of %d: %s", recordNumber, maxRecords, error);

Using

String.format("%02d", num)

Is probably the best option.


Yet another way

String text = (num < 10 ? "0" : "") + num;

EDIT: The code is short enough that the JIT can compile it to nothing. ;)

long start = System.nanoTime();
for(int i=0;i<100000;i++) {
    for(int num=1;num<100;num++) {
        String text = (num < 10 ? "0" : "") + num;
    }
}
long time = System.nanoTime() - start;
System.out.println(time/99/100000);

prints

0

You can do this with NumberFormat:

NumberFormat format = new NumberFormat();
format.setMinimumIntegerDigits(2);
System.out.println(format.format(1));

Note - String.format() is a Java 5 method.

If you're using Java 5 or above you can do:

String.format("%02d", 1);

as mentioned in other answers.

Tags:

Java