Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which API can I use to format an int to 2 digits?

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 )

like image 308
Jimmy Avatar asked Oct 20 '10 08:10

Jimmy


People also ask

How to print 2 zeros after Decimal in Java?

To be able to print any given number with two zeros after the decimal point, we'll use one more time DecimalFormat class with a predefined pattern: public static double withTwoDecimalPlaces(double value) { DecimalFormat df = new DecimalFormat("#. 00"); return new Double(df.

What is %02d?

%02d means an integer, left padded with zeros up to 2 digits.


2 Answers

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);
like image 162
aioobe Avatar answered Oct 22 '22 05:10

aioobe


String class actually do formatting.

For your case, try:

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

like image 41
medopal Avatar answered Oct 22 '22 06:10

medopal