Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left pad zeroes to a string variable in java

Tags:

java

string

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

like image 401
the_dopamine Avatar asked Nov 01 '11 17:11

the_dopamine


People also ask

How can I pad a string with zeros on the left?

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.

How do you assign a zero to a string in Java?

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.

How do you add padding to a string in Java?

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.

What is left padding in Java?

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)


1 Answers

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

like image 168
Dinesh Appuhami Avatar answered Oct 12 '22 23:10

Dinesh Appuhami