Home » Java » Add leading zeroes to number in Java? [duplicate]

Add leading zeroes to number in Java? [duplicate]

Posted by: admin November 2, 2017 Leave a comment


This question already has an answer here:


String.format (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 – to pad with zeros
  • 3 – to set width to 3

Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:

String format = String.format("%%0%dd", digits);
String result = String.format(format, num);
return result;

In this case, you’re creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:

%% --> %
0  --> 0
%d --> <value of digits>
d  --> d

So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.


Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

static String intToString(int num, int digits) {
    assert digits > 0 : "Invalid number of digits";

    // create variable length array of zeros
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    // format number as String
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

    return df.format(num);


How about just:

public static String intToString(int num, int digits) {
    String output = Integer.toString(num);
    while (output.length() < digits) output = "0" + output;
    return output;


In case of your jdk version less than 1.5, following option can be used.

    int iTest = 2;
    StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
    System.out.println(sTest.substring(sTest.length()-6, sTest.length()));