I have an int between 1 - 99. How do I get it to always be a double digit, ie: 01, 04, 21?
format() method, which will let you do exactly what you want: String s = String. format("%02d", someNumber);
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding.
Presumably you mean to store the number in a String.
Since JDK1.5 there has been the String.format() method, which will let you do exactly what you want:
String s = String.format("%02d", someNumber);
One of the nice things about String.format() is that you can use it to build up more complex strings without resorting to lots of concatenation, resulting in much cleaner code.
String logMessage = String.format("Error processing record %d of %d: %s", recordNumber, maxRecords, error);
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
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