How to format a Java string with leading zero?
369,117
Solution 1
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.)
Solution 2
public class LeadingZerosExample {
public static void main(String[] args) {
int number = 1500;
// String format below will add leading zeros (the %0 syntax)
// to the number above.
// The length of the formatted string will be 7 characters.
String formatted = String.format("%07d", number);
System.out.println("Number with leading zeros: " + formatted);
}
}
Solution 3
StringUtils.leftPad(yourString, 8, '0');
This is from commons-lang. See javadoc
Solution 4
This is what he was really asking for I believe:
String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple");
output:
000Apple
Solution 5
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.
Related videos on Youtube
Author by
Roy
Updated on April 03, 2022Comments
-
Roy about 2 years
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?
-
Roy over 13 yearsbut I would like to adding leading zero before a string instead of an int.
-
Bozho over 13 yearsWhy not use commons-lang? It has a loot of useful extras.
-
Bart Kiers over 13 yearsThe -1 is probably because this is a not so good example: you're using "magic numbers" and are concatenating Strings, something that should be replaced by using a StringBuilder or StringBuffer.
-
kaliatech over 13 yearsEven if you are not able to use commons-lang, you can easily copy the source from StringUtils to make your own function. That would be a much better general solution than the selected answer. docjar.com/html/api/org/apache/commons/lang/…
-
Bart Kiers over 13 yearswhat if that would be the only method the library is used for? Perhaps the added library is even many times bigger than the app it is used in. I can imagine quite some reasons not to add a commons library in an application. Don't get me wrong: I agree, it contains very useful stuff, but I understand the reluctance to stuff an app full of external JARs if the benefit is not needing to write just one (or a couple) of methods.
-
Arne Deutsch over 13 years@kaliatech: yes, a much better GENERAL solution, but if he don't want to use the library probably a focused (short) solution is more appropriate.
-
Amy B over 13 yearsThat's pretty clever -- but it took me about 30 seconds to "get it". I think a more readable solution would be better.
-
Casey Murray over 10 yearsThis is an -excellent- solution when you are embedding software on something without much space and the extra libraries just aren't an option. Thanks!!
-
Dakkaron almost 10 yearsThis version is crazy fast! I love it.
-
Deian over 9 yearsThis is fast & works for whatever length. public static String prefixZeros(String value, int len) { char[] t = new char[len]; int l = value.length(); int k = len-l; for(int i=0;i<k;i++) { t[i]='0'; } value.getChars(0, l, t, k); return new String(t); } Yes, there is no formatting here :( see code below.
-
JavaDev over 9 yearsYou can use StringUtils or DecimalFormat for Java 1.4 and below. Check here javadevnotes.com/java-integer-to-string-with-leading-zeros
-
HankCa about 8 years@Mathu honestly that is not difficult to understand. Two strings are concatenated (joined together) and the first 5 characters are extracted from it. No magic. Not very sensible in this case (for fixed string Apple) but easy to understand.
("0000" + theString).substring(theString.length())
is more realistic. This padstheString
with leading zeros. Sorry couldn't resist adding this comment :) -
Jan over 7 years@Dici It does "work" for a larger size, it just truncates your string to 8 characters .... So it depends on your expected behavior for longer-than-8-character strings (which wasn't specified by the OP)
-
Dici over 7 yearsThis solution has a short syntax but it's not "crazy fast". If you're lucky the compiler will optimize it but essentially the real "fast" way to do this is using a
StringBuilder
, and it takes a loop to fill it. If the requirement is really to only truncate 8-characters strings that's ok, although that's a very narrow use-case, but this solution can never be called fast. It is just short. -
nbrooks over 7 yearsDoesn't work for the general case; if you substitute "Apple" with a string of length 8 characters (which is possible in OP's case) this throws a
DuplicateFormatFlagsException
(because of the00
in the format string). If you substitute a string longer than 8 characters, this throws anIllegalFormatFlagsException
(because of the negative number). -
Nachi over 7 yearsTo answer the "Why not use commons-lang? It has a loot of useful extras." question with a concrete example. Xiaomi ships an outdated version of commons-lang on its Android devices. Including a newer version in your app leads to classloader conflicts, so commons-lang can no longer be used in any Android project.
-
Abhinav Puri over 7 yearsYou are right, but what about this then :
String.format("%0"+ (9 - "Apple".length() )+"d%s",0 ,"Apple").substring(0,8);
. Now you wont have this exception. -
Toby Speight about 7 yearsWhilst this code snippet is welcome, and may provide some help, it would be greatly improved if it included an explanation of how it addresses the question. Without that, your answer has much less educational value - remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.
-
Lluis Martinez about 7 years@Nachi even if outdated StringUtils.leftPad should exist
-
Zoidberg almost 7 yearsBy far the best answer. Apache commons StringUtils is a simple yet extremely helpful library.
-
Admin over 6 yearsJust wanna add
String.format("%0"+ (9 - "Apple".length() )+"d%s",0 ,"Apple").substring(0,8);
is WRONG, it should beString.format("%0"+ (9 - "Apple".length() )+"d%s",0 ,"Apple").substring(1,9);
. -
Erdi İzgi over 6 yearsThen you may want to split the string first, apply the operation above to the first split value, than concatenate the rest of the split values.
-
Z fp almost 5 years@Variag use
%07s
instead of%07d
, you will get aFormatFlagsConversionMismatchException
. you can try it. -
Abhishek over 4 yearsThis saved a lot of time and it's neat and clean as well.
-
Mikolasan over 4 yearsUpdated Javadoc API links: current stable release 3.9, legacy release 2.6
-
Lluís Suñol over 4 yearsThough it works, I wouldn't recommend using this way. It's not as clean as using String.format, which essentially is what you are trying to do: give a number a String format. By using this you need to read the statement twice to find out what it is doing.
-
user1697575 about 4 years@user4231709 Great solution! +1
-
Bhdr over 3 yearsString.format("%08d", anInteger); // this worked for me. String version throws exception
-
Kaninchen about 3 yearsThis is not a good answer due to
val - 8
isn't correct logic for the Java and will cause compile error -
Heiner almost 3 yearsThis won't run.
-
Nemolovich almost 3 yearsAgree with @Heiner, formatting String with number format will fail.
-
Kröw over 2 years@AmyB This is extremely readable.
-
Kröw over 2 yearsWeird!
int number = "Apple";
didn't work! How odd? 🤔 -
袁文涛 over 2 years
StringUtils.right(("00000000" + "Apple"),8)
-
user1561783 about 2 yearsone would have to include apache commons lang jar into your class path. Why ? when you already have String.Format. See @Alex-Rashkov answer below.