Left pad an integer in Java with zeros

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 20-Dec-2018 07:57:59
Advertisements