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.

Share:
369,117

Related videos on Youtube

Roy
Author by

Roy

Updated on April 03, 2022

Comments

  • Roy
    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
    Roy over 13 years
    but I would like to adding leading zero before a string instead of an int.
  • Bozho
    Bozho over 13 years
    Why not use commons-lang? It has a loot of useful extras.
  • Bart Kiers
    Bart Kiers over 13 years
    The -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
    kaliatech over 13 years
    Even 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
    Bart Kiers over 13 years
    what 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
    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
    Amy B over 13 years
    That's pretty clever -- but it took me about 30 seconds to "get it". I think a more readable solution would be better.
  • Casey Murray
    Casey Murray over 10 years
    This 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
    Dakkaron almost 10 years
    This version is crazy fast! I love it.
  • Deian
    Deian over 9 years
    This 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
    JavaDev over 9 years
    You can use StringUtils or DecimalFormat for Java 1.4 and below. Check here javadevnotes.com/java-integer-to-string-with-leading-zeros
  • HankCa
    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 pads theString with leading zeros. Sorry couldn't resist adding this comment :)
  • Jan
    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
    Dici over 7 years
    This 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
    nbrooks over 7 years
    Doesn'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 the 00 in the format string). If you substitute a string longer than 8 characters, this throws an IllegalFormatFlagsException (because of the negative number).
  • Nachi
    Nachi over 7 years
    To 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
    Abhinav Puri over 7 years
    You 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
    Toby Speight about 7 years
    Whilst 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
    Lluis Martinez about 7 years
    @Nachi even if outdated StringUtils.leftPad should exist
  • Zoidberg
    Zoidberg almost 7 years
    By far the best answer. Apache commons StringUtils is a simple yet extremely helpful library.
  • Admin
    Admin over 6 years
    Just wanna add String.format("%0"+ (9 - "Apple".length() )+"d%s",0 ,"Apple").substring(0,8); is WRONG, it should be String.format("%0"+ (9 - "Apple".length() )+"d%s",0 ,"Apple").substring(1,9); .
  • Erdi İzgi
    Erdi İzgi over 6 years
    Then 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
    Z fp almost 5 years
    @Variag use %07s instead of %07d, you will get a FormatFlagsConversionMismatchException. you can try it.
  • Abhishek
    Abhishek over 4 years
    This saved a lot of time and it's neat and clean as well.
  • Mikolasan
    Mikolasan over 4 years
    Updated Javadoc API links: current stable release 3.9, legacy release 2.6
  • Lluís Suñol
    Lluís Suñol over 4 years
    Though 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
    user1697575 about 4 years
    @user4231709 Great solution! +1
  • Bhdr
    Bhdr over 3 years
    String.format("%08d", anInteger); // this worked for me. String version throws exception
  • Kaninchen
    Kaninchen about 3 years
    This is not a good answer due to val - 8 isn't correct logic for the Java and will cause compile error
  • Heiner
    Heiner almost 3 years
    This won't run.
  • Nemolovich
    Nemolovich almost 3 years
    Agree with @Heiner, formatting String with number format will fail.
  • Kröw
    Kröw over 2 years
    @AmyB This is extremely readable.
  • Kröw
    Kröw over 2 years
    Weird! int number = "Apple"; didn't work! How odd? 🤔
  • 袁文涛
    袁文涛 over 2 years
    StringUtils.right(("00000000" + "Apple"),8)
  • user1561783
    user1561783 about 2 years
    one would have to include apache commons lang jar into your class path. Why ? when you already have String.Format. See @Alex-Rashkov answer below.