How to format a Java string with leading zero? How to format a Java string with leading zero? java java

How to format a Java string with leading zero?


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