Display numbers with leading zeroes in Java

Java 8Object Oriented ProgrammingProgramming

To display numbers with leading zeros in Java, useDecimalFormat("000000000000").

Let us first set the format with DecimalFormat class −

DecimalFormat decFormat = new DecimalFormat("000000000000");

Now, let us display some numbers with leading zeros −

String res = decFormat.format(298989);
System.out.println(res);
res = decFormat.format(565);
System.out.println(res);

The following is an example −

Example

 Live Demo

import java.text.DecimalFormat;
public class Demo {
   public static void main(String args[]) {
      DecimalFormat decFormat = new DecimalFormat("000000000000");
      String res = decFormat.format(298989);
      System.out.println(res);
      res = decFormat.format(565);
      System.out.println(res);
      res = decFormat.format(38989);
      System.out.println(res);
      res = decFormat.format(78768768);
      System.out.println(res);
      res = decFormat.format(298989);
      System.out.println(res);
   }
}

Output

000000298989
000000000565
000000038989
000078768768
000000298989
raja
Published on 21-Dec-2018 10:56:55
Advertisements