I have a string variable of 10 digits, if something less than 10 i need to append '0' before the variable. Example if the string is 9909909 it should be returned as 0009909909. how to do it in java
To pad zeros to a string, use the str. zfill() method. It takes one argument: the final length of the string you want and pads the string with zeros to the left.
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding.
Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method.
In Java leftPad() is a static method of the StringUtils class which is used to left pad spaces to the given string. There are three variations of the method: leftPad(final String str, final int size) leftPad(final String str, final int size, final char padChar)
Try Apache StringUtils class.
import org.apache.commons.lang.StringUtils;
...
String seqNumber = "123"
int seqNumberLength = 10;
String result = StringUtils.leftPad(seqNumber, seqNumberLength,"0")
result is 0000000123
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With