Advertisement
Advertisement


How to format a Java string with leading zero?


Question

Here is the String, for example:

"Apple"

and I would like to add zero to fill in 8 chars:

"000Apple"

How can I do so?

2015/05/22
1
195
5/22/2015 11:47:40 AM

Accepted Answer

In case you have to do it without the help of a library:

("00000000" + "Apple").substring("Apple".length())

(Works, as long as your String isn't longer than 8 chars.)

2010/10/29
287
10/29/2010 12:48:21 PM


 StringUtils.leftPad(yourString, 8, '0');

This is from commons-lang. See javadoc

2020/03/09

This is what he was really asking for I believe:

String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple"); 

output:

000Apple
2015/07/16

You can use the String.format method as used in another answer to generate a string of 0's,

String.format("%0"+length+"d",0)

This can be applied to your problem by dynamically adjusting the number of leading 0's in a format string:

public String leadingZeros(String s, int length) {
     if (s.length() >= length) return s;
     else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}

It's still a messy solution, but has the advantage that you can specify the total length of the resulting string using an integer argument.

2014/11/13

Using Guava's Strings utility class:

Strings.padStart("Apple", 8, '0');
2016/05/23

You can use this:

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
2016/03/15

Source: https://stackoverflow.com/questions/4051887
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]