I have an int between 1 - 99. How do I get it to always be a double digit, ie: 01, 04, 21?
You can do this with NumberFormat:
NumberFormat format = new NumberFormat();
format.setMinimumIntegerDigits(2);
System.out.println(format.format(1));
Note - String.format() is a Java 5 method.
If you're using Java 5 or above you can do:
String.format("%02d", 1);
as mentioned in other answers.
You can do this by
String.format("%02d", 1)
I think, I should add the link to the official Java documentation on formatting numeric outputs.
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Sample Snipplet: Prints 00 up to 100
class Main {
public static void main(String[] args) {
for(int i=0;i<=100;i++){
System.out.println(String.format("%02d", i));
}
}
}
Output:
00
01
...
10
...
100
Or you could just use printf instead of String.format
for (int i = 0; i <= 100; i++) {
System.out.printf("%02d%n",i);
}
Yet another way
String text = (num < 10 ? "0" : "") + num;
EDIT: The code is short enough that the JIT can compile it to nothing. ;)
long start = System.nanoTime();
for(int i=0;i<100000;i++) {
for(int num=1;num<100;num++) {
String text = (num < 10 ? "0" : "") + num;
}
}
long time = System.nanoTime() - start;
System.out.println(time/99/100000);
prints
0