views:

63

answers:

3

What API can I use to format an int to be 2 digits long?

For example, in this loop

for (int i = 0; i<100; i++)
{
   System.out.println("i is " + i);
}

What can I use to make sure i is printed out like 01, 02, 10, 55 etc (assuming a range of 01-99 )

+9  A: 

You could simply do

System.out.printf("i is %02d%n", i);

Have a look at the documentation for Formatter for details. Relevant parts are:

  • The format specifiers for general, character, and numeric types have the following syntax:

        %[argument_index$][flags][width][.precision]conversion

(In this particular case, you have 0 as flag, 2 as width, and d as conversion.)

Conversion
'd'    integral      The result is formatted as a decimal integer

Flags
'0'       The result will be zero-padded


This formatting syntax can be used in a few other places as well, for instance like this: String str = String.format("i is %02d", i);

aioobe
+2  A: 

You can use the DecimalFormat object.

DecimalFormat formatter = new DecimalFormat("#00.###");
int test = 1;

System.out.println(formatter.format(test));

Will print "01".

EMMERICH
+1  A: 

String class actually do formatting.

For your case, try:

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

medopal