This question already has an answer here:
- How can I pad a String in Java? 27 answers
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.
I have used this:
Result: 00123
I hope you find it useful!
the second parameter is the desired output length
"0" is the padding char
If you need performance and know the maximum size of the string use this:
Be aware of the maximum string size. If it is bigger then the StringBuffer size, you'll get a
java.lang.StringIndexOutOfBoundsException
.I prefer this code:
and then:
An old question, but I also have two methods.
For a fixed (predefined) length:
For a variable length:
This will pad left any string to a total width of 10 without worrying about parse errors:
If you want to pad right:
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:
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.