8

Possible Duplicate:
How to format a number 0..9 to display with 2 digits (it’s NOT a date)

How can I write an integer number with two digits in Java? For example if the integer is less than 10, the program should return 01 to 09. I need that 0 in front of the one digit number. Something like %.2f for double type.

Community
  • 1
  • 1
pidev
  • 131
  • 1
  • 1
  • 10

3 Answers3

22

Assuming that, since you know about %.2f for formatting double, so you at least know about formatting.

So, to format your integers appropriately, you can prepend a 0 before %2d to pad your numbers with 0 at the beginning: -

int i = 9;
System.out.format("%02d\n", i);  // Will print 09
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
17

Use String.format method...

Example

  System.out.println(String.format("%02d", 5));
  System.out.println(String.format("%02d", 55));
  System.out.println(String.format("%02d", 15));
Subba
  • 396
  • 2
  • 13
1

"Write" how? Assuming you mean from a PrintStream, you can use printf for that. Formatting details here. I believe the format string would be %02d.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875