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: 29-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements