Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write integer with two digits? [duplicate]

Tags:

java

integer

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.

like image 371
pidev Avatar asked Oct 22 '12 10:10

pidev


3 Answers

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
like image 199
Rohit Jain Avatar answered Oct 03 '22 17:10

Rohit Jain


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));
like image 34
Subba Avatar answered Oct 03 '22 17:10

Subba


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

like image 32
T.J. Crowder Avatar answered Oct 03 '22 17:10

T.J. Crowder