Wednesday, June 3, 2015

How to add leading zeroes in front of a number by using Java?

I have some integers. I would like to add leading zeroes if they are less than 100. For example, If the number is 1,  it would be converted to 001. If the number is 10, it would be as 010.

By using Java 7 and above, we can simply to do this by using the following line.

 int i =0;  
 int n=10;  
 System.out.println(String.format("%03d", i));  
 System.out.println(String.format("%03d", n));