Left pad an integer in Java with zeros



Let us see an example first to understand how an integer looks with left padding −

888 //left padding with spaces
0000000999 //left padding with 7 zeros

Let us see an example to left pad a number with zero −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      int val = 9899;
      System.out.println(String.format("%05d",val));
   }
}

Output

09899

Let us see another example that pads a greater number of zeros −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      int val = 9899;
      System.out.println(String.format("%010d", val));
   }
}

Output

0000009899
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements