Java Program to add leading zeros to a number



To add leading zeros to a number, you need to format the output. Let’s say we need to add 4 leading zeros to the following number with 3 digits.

int val = 290;

For adding 4 leading zeros above, we will use %07d i.e. 4+3 = 7. Here, 3, as shown above, is the number with 3 digits.

String.format("%07d", val);

The following is the final example.

Example

 Live Demo

import java.util.Formatter;
public class Demo {
    public static void main(String args[]) {
       int val = 290;
       System.out.println("Integer: "+val);
       String formattedStr = String.format("%07d", val);
       System.out.println("With leading zeros = " + formattedStr);
    }
}

Output

Integer: 290
With leading zeros = 0000290
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements