Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 1 to 01

Tags:

I have an int between 1 - 99. How do I get it to always be a double digit, ie: 01, 04, 21?

like image 271
Roger Avatar asked Mar 04 '11 17:03

Roger


People also ask

How do you convert a single digit to a double digit in Java?

format() method, which will let you do exactly what you want: String s = String. format("%02d", someNumber);

How do you add leading zeros in Java?

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.


2 Answers

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); 
like image 127
Adam Batkin Avatar answered Oct 19 '22 01:10

Adam Batkin


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 
like image 41
Peter Lawrey Avatar answered Oct 19 '22 03:10

Peter Lawrey