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
Updated on: 2020-06-29T05:32:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements