How to add leading zeros to a number in Java

In this tutorial, we are going to learn how to add leading zeros to a number in Java.

We can add leading zeros in a number by format the output using a format string.

Add leading zeros using String.format() function in Java

For example, if we want to add 3 leading zeros value 2529.

First, we have to import java.util.formatter.

Code:-

import java.util.Formatter;

Then inside the class, we have to initialize the value 2529 to any variable and then we have to use String.format() function to add leading zeros.

Code:-

      int var = 2529;
      
      String formattedvar = String.format("%08d", var)

In the above code, we store the formatted value in formattedvar variable,

% denotes that it is a formatting instruction
may be a flag which says pad with zero
8 denotes the length of formatted String,
d is for decimal which suggests subsequent argument should be an integral value

EXAMPLE CODE

import java.util.Formatter;
public class LeadZero {
   public static void main(String args[]) {
      int var = 2529;
      String formattedvar = String.format("%08d", var);
      System.out.println("With leading zeros = " + formattedvar);
   }
}


Output:-

With leading zeros = 00002529

EXAMPLE 2

import java.util.Formatter;
public class LeadZero {
   public static void main(String args[]) {
      float var = 2529.532f;
      String formattedvar = String.format("%08f", var);
      System.out.println("With leading zeros = " + formattedvar);
   }
}


Output:-

With leading zeros = 2529.531982

Also read: how to add a char to a string in Java

Leave a Reply

Your email address will not be published. Required fields are marked *