296

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.

0

20 Answers 20

424

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Was pulling out my hair because I didn't see that I had to perform the Integer.parseInt().
Additionally, for those who want to pad their numbers/strings with something else that isn't "0", change the %0 to %yourchoice.
Just a word of caution: This solution failed for larger Integer values (ex: "9999999999"); hence I went with Oliver Michels solution using Apache commons.
In case of large Integer values like "9999999999", String.format() supports BigInteger like so: String.format("%010d", new BigInteger("9999999999"))
@micnguyen You sure? the "0" after the "%" is a flag. The possible flags are very limited.
169
String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0") 

the second parameter is the desired output length

"0" is the padding char

3 Comments

Just as a reminder... String is immutable (see String is immutable. What exactly is the meaning?), 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");.
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".
another reminder - if the length of the value to be padded is greater than the specified length of the desired padding, then the original string is returned, i.e. it is not truncated. source
125

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.

6 Comments

May need to be careful with the length of the string that is being padded-- the call to substring() can throw an IndexOutOfBoundsException.
plus the performance? I think it creates 3 different strings, if I am not wrong.
Why was this upvoted? It's related to JavaScript, not Java?
@mhvelplund It was edited Mar 2 by Rick, I think he just made a mistake, I have undone the change.
Thanks @Magnus, that was definitely a mistake
|
58
String str = "129018"; String str2 = String.format("%10s", str).replace(' ', '0'); System.out.println(str2); 

3 Comments

this is a more round-about approach than the accepted answer.
@PaulW: but it works for strings
This wouldn't work if the string had spaces in it...
55
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(); 

2 Comments

+1 for being the only correct answer that doesn't use an external library
Just observe the buffer size of StringBuilder, its default is 16, and for big formated sizes set correctly the buffer sizer, like in: StringBuilder sb = new StringBuilder();
28

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)

1 Comment

FYI, link is dead.
16

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

Comments

11

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.

2 Comments

This works great. Luckily, I was dealing with binary numbers so I knew the max would be 8. Thanks.
This is not elegant at all. Everytime you want to pad, you have to create a variable.
7

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(); } 

Comments

7

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

2 Comments

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.
Yes, are you right! Patched now! Thank @Passkit
6

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" 

Comments

4

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

1 Comment

I prefer simple logical approaches such as this over the other 'clever' answers, but I would suggest using StringBuffer or StringBuilder.
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) 

Comments

2

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

Comments

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

Comments

1

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

2 Comments

the dollar sign to who doesnt know what it is: stackoverflow.com/a/33458861/1422630
this would still require a replace of spaces to zeroes
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'

Comments

1

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!

Comments

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()); } } 

1 Comment

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.