264

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.

Community
  • 1
  • 1
jai
  • 19,731
  • 28
  • 83
  • 116

20 Answers20

384

If your string contains numbers only, you can make it an integer and then do padding:

String.format("%010d", Integer.parseInt(mystring));

If not I would like to know how it can be done.

Community
  • 1
  • 1
khachik
  • 26,041
  • 7
  • 52
  • 90
  • 2
    Was pulling out my hair because I didn't see that I had to perform the Integer.parseInt(). – JRSofty Jun 15 '12 at 12:49
  • 9
    Additionally, for those who want to pad their numbers/strings with something else that isn't "0", change the `%0` to `%yourchoice`. – micnguyen May 24 '13 at 00:54
  • 4
    Just a word of caution: This solution failed for larger Integer values (ex: "9999999999"); hence I went with Oliver Michels solution using Apache commons. – oneworld May 31 '14 at 00:19
  • 8
    In case of large Integer values like "9999999999", `String.format()` supports `BigInteger` like so: `String.format("%010d", new BigInteger("9999999999"))` – real_paul Dec 23 '15 at 12:28
  • 4
    @micnguyen You sure? the "0" after the "%" is a flag. The possible flags are very limited. – Gustavo Jul 28 '17 at 15:14
154
String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")

the second parameter is the desired output length

"0" is the padding char

reto
  • 14,837
  • 7
  • 50
  • 62
Oliver Michels
  • 2,659
  • 1
  • 15
  • 14
  • 26
    Just as a reminder... `String` is immutable (see *[String is immutable. What exactly is the meaning?](http://stackoverflow.com/q/8798403/1064325)*), so `StringUtils.leftPad(variable, 10, "0");` won't change the `variable`'s value. You'd need to assign the result to it, like this: `variable = StringUtils.leftPad(variable, 10, "0");`. – falsarella May 19 '15 at 13:55
  • It would be nice to see the output of the suggested command without the need to run it. Heard somewhere that a good is a lazy one :) Anyhow, here it is: StringUtils.leftPad("1", 3, '0') -> "001". – AlikElzin-kilaka Oct 28 '20 at 16:41
117

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.

Rick Hanlon II
  • 16,833
  • 7
  • 42
  • 52
54
String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);
Satish
  • 557
  • 4
  • 2
53
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();
Thom Wiggers
  • 6,474
  • 1
  • 37
  • 58
thejh
  • 41,293
  • 15
  • 89
  • 105
22

You may use apache commons StringUtils

StringUtils.leftPad("129018", 10, "0");

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#leftPad(java.lang.String,%20int,%20char)

Community
  • 1
  • 1
thk
  • 229
  • 1
  • 2
14

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

Nagarajan S R
  • 1,202
  • 1
  • 18
  • 29
10

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.

Jasper de Vries
  • 13,693
  • 6
  • 54
  • 86
Haroldo Macedo
  • 403
  • 4
  • 7
6

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();
    }
user85421
  • 27,680
  • 10
  • 62
  • 85
5

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"  
Tho
  • 17,326
  • 6
  • 51
  • 41
5

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"));
strobering
  • 136
  • 2
  • 6
  • 1
    I think you have your left an right mixed up. `StrMgr.leftPad` is appending padding to the string and `StrMgr.rightPad` is prepending. For me (at least), I would expect left pad to add padding to the front of the string. – PassKit Jan 16 '17 at 07:21
  • Yes, are you right! Patched now! Thank @Passkit – strobering Feb 15 '17 at 01:49
3

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");

Community
  • 1
  • 1
Sithu
  • 4,374
  • 7
  • 55
  • 98
  • 1
    I prefer simple logical approaches such as this over the other 'clever' answers, but I would suggest using StringBuffer or StringBuilder. – Henry Aug 10 '18 at 22:25
2

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)
nullpotent
  • 9,013
  • 1
  • 29
  • 41
2

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

sh3r1
  • 21
  • 2
1

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

Arun
  • 11
  • 1
1

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'

1

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

Prabhu
  • 4,977
  • 3
  • 31
  • 40
0
    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());
    }
}
bockymurphy
  • 51
  • 1
  • 4
  • Why are you returning an error in the first case, and not an exception (if that is your requirement), you are breaking the return pattern of the function. why would you not just return the string value of the number as in the second case (as that is also a valid input for a generic method) – A myth Apr 10 '14 at 15:50
0

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);
Fathah Rehman P
  • 7,353
  • 3
  • 36
  • 41
0

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!

user207421
  • 289,834
  • 37
  • 266
  • 440