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.
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
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));
"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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With