Blog Archive

Java add leading zeros to a number and convert to String

Sometimes during dealing with legacy systems we need to pass numeric values in fixed length with leading zeros. Now in Java we just have an integer value. So how do we convert an integer in Java to a string value with fixed length of 9 with leading zeros. Here is a sample program that uses the String.format() method to add leading zeros to a number.

Sample Java source code

package com.as400samplecode;

public class AddLeadingZeros {

    public static void main(String[] args) {

        int myNumber = 654321;
        String stringNumber = String.format("%09d", myNumber);
        System.out.println("Number with leading zeros: " + stringNumber);
       
    }

}

Program result

Number with leading zeros: 000654321

Explanation

The format string can contain zero, one, or more format specifiers. The general form of a format specifier is:

%[argument_index$][flags][width][.precision]conversion

where things in square brackets are optional, and conversion is a character indicating the conversion to be applied to the corresponding variable value. The only required characters in the format specifier is the percent sign % and the conversion character.

In the above example for converting a number to a string with leading zeros we used the following
  • % sign
  • flag "0" that make the result zero-padded
  • width of 9
  • "d" as the conversion