Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a Java string with leading zero?

People also ask

How do you add a leading zero to a string?

You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string.

What is %d and %s in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

How do you add a leading zero to a double in Java?

Yes, include the + character, e.g. String. format("%+014.2f", -2.34); .


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);
    }
}

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.)


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

This is from commons-lang. See javadoc


This is what he was really asking for I believe:

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

output:

000Apple