[java] Left padding a String with Zeros

I've seen similar questions here and here.

But am not getting how to left pad a String with Zero.

input: "129018" output: "0000129018"

The total output length should be TEN.

This question is related to java string padding

The answer is


String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);

An old question, but I also have two methods.


For a fixed (predefined) length:

    public static String fill(String text) {
        if (text.length() >= 10)
            return text;
        else
            return "0000000000".substring(text.length()) + text;
    }

For a variable length:

    public static String fill(String text, int size) {
        StringBuilder builder = new StringBuilder(text);
        while (builder.length() < size) {
            builder.append('0');
        }
        return builder.toString();
    }

String str = "129018";
StringBuilder sb = new StringBuilder();

for (int toPrepend=10-str.length(); toPrepend>0; toPrepend--) {
    sb.append('0');
}

sb.append(str);
String result = sb.toString();

Based on @Haroldo MacĂȘdo's answer, I created a method in my custom Utils class such as

/**
 * Left padding a string with the given character
 *
 * @param str     The string to be padded
 * @param length  The total fix length of the string
 * @param padChar The pad character
 * @return The padded string
 */
public static String padLeft(String str, int length, String padChar) {
    String pad = "";
    for (int i = 0; i < length; i++) {
        pad += padChar;
    }
    return pad.substring(str.length()) + str;
}

Then call Utils.padLeft(str, 10, "0");



Here is a solution based on String.format that will work for strings and is suitable for variable length.

public static String PadLeft(String stringToPad, int padToLength){
    String retValue = null;
    if(stringToPad.length() < padToLength) {
        retValue = String.format("%0" + String.valueOf(padToLength - stringToPad.length()) + "d%s",0,stringToPad);
    }
    else{
        retValue = stringToPad;
    }
    return retValue;
}

public static void main(String[] args) {
    System.out.println("'" + PadLeft("test", 10) + "'");
    System.out.println("'" + PadLeft("test", 3) + "'");
    System.out.println("'" + PadLeft("test", 4) + "'");
    System.out.println("'" + PadLeft("test", 5) + "'");
}

Output: '000000test' 'test' 'test' '0test'


    int number = -1;
    int holdingDigits = 7;
    System.out.println(String.format("%0"+ holdingDigits +"d", number));

Just asked this in an interview........

My answer below but this (mentioned above) is much nicer->

String.format("%05d", num);

My answer is:

static String leadingZeros(int num, int digitSize) {
    //test for capacity being too small.

    if (digitSize < String.valueOf(num).length()) {
        return "Error : you number  " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";

        //test for capacity will exactly hold the number.
    } else if (digitSize == String.valueOf(num).length()) {
        return String.valueOf(num);

        //else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError 

        //else calculate and return string
    } else {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digitSize; i++) {
            sb.append("0");
        }
        sb.append(String.valueOf(num));
        return sb.substring(sb.length() - digitSize, sb.length());
    }
}

Use Google Guava:

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Sample code:

Strings.padStart("129018", 10, '0') returns "0000129018"  

String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")

the second parameter is the desired output length

"0" is the padding char


I have used this:

DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));

Result: 00123

I hope you find it useful!


Right padding with fix length-10: String.format("%1$-10s", "abc") Left padding with fix length-10: String.format("%1$10s", "abc")


This will pad left any string to a total width of 10 without worrying about parse errors:

String unpadded = "12345"; 
String padded = "##########".substring(unpadded.length()) + unpadded;

//unpadded is "12345"
//padded   is "#####12345"

If you want to pad right:

String unpadded = "12345"; 
String padded = unpadded + "##########".substring(unpadded.length());

//unpadded is "12345"
//padded   is "12345#####"  

You can replace the "#" characters with whatever character you would like to pad with, repeated the amount of times that you want the total width of the string to be. E.g. if you want to add zeros to the left so that the whole string is 15 characters long:

String unpadded = "12345"; 
String padded = "000000000000000".substring(unpadded.length()) + unpadded;

//unpadded is "12345"
//padded   is "000000000012345"  

The benefit of this over khachik's answer is that this does not use Integer.parseInt, which can throw an Exception (for example, if the number you want to pad is too large like 12147483647). The disadvantage is that if what you're padding is already an int, then you'll have to convert it to a String and back, which is undesirable.

So, if you know for sure that it's an int, khachik's answer works great. If not, then this is a possible strategy.


To format String use

import org.apache.commons.lang.StringUtils;

public class test {

    public static void main(String[] args) {

        String result = StringUtils.leftPad("wrwer", 10, "0");
        System.out.println("The String : " + result);

    }
}

Output : The String : 00000wrwer

Where the first argument is the string to be formatted, Second argument is the length of the desired output length and third argument is the char with which the string is to be padded.

Use the link to download the jar http://commons.apache.org/proper/commons-lang/download_lang.cgi


The solution by Satish is very good among the expected answers. I wanted to make it more general by adding variable n to format string instead of 10 chars.

int maxDigits = 10;
String str = "129018";
String formatString = "%"+n+"s";
String str2 = String.format(formatString, str).replace(' ', '0');
System.out.println(str2);

This will work in most situations


Here's another approach:

int pad = 4;
char[] temp = (new String(new char[pad]) + "129018").toCharArray()
Arrays.fill(temp, 0, pad, '0');
System.out.println(temp)

Here's my solution:

String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);

Output: 00000101


Check my code that will work for integer and String.

Assume our first number is 129018. And we want to add zeros to that so the the length of final string will be 10. For that you can use following code

    int number=129018;
    int requiredLengthAfterPadding=10;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);

I prefer this code:

public final class StrMgr {

    public static String rightPad(String input, int length, String fill){                   
        String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
        return pad.substring(0, length);              
    }       

    public static String leftPad(String input, int length, String fill){            
        String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
        return pad.substring(pad.length() - length, pad.length());
    }
}

and then:

System.out.println(StrMgr.leftPad("hello", 20, "x")); 
System.out.println(StrMgr.rightPad("hello", 20, "x"));

If you need performance and know the maximum size of the string use this:

String zeroPad = "0000000000000000";
String str0 = zeroPad.substring(str.length()) + str;

Be aware of the maximum string size. If it is bigger then the StringBuffer size, you'll get a java.lang.StringIndexOutOfBoundsException.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to padding

Can we define min-margin and max-margin, max-padding and min-padding in css? Does bootstrap have builtin padding and margin classes? Adding space/padding to a UILabel How to adjust gutter in Bootstrap 3 grid system? Why is there an unexplainable gap between these inline-block div elements? How to increase the distance between table columns in HTML? Absolute positioning ignoring padding of parent Remove all padding and margin table HTML and CSS Style the first <td> column of a table differently Using margin / padding to space <span> from the rest of the <p>