Share this page 

Display numbers with leading zeroesTag(s): String/Number


jdk1.5+
Using String.format()
public class Test {
   public static void main(String args[]) throws Exception {
      String value = String.format("%09d",42);
      System.out.println(value);
      // output :  000000042
   }
 }
A dynamic way to specify the number of 0 to be padded if needed:
public class NumberUtils {
  private NumberUtils() {}

  public static String formatLong(long n, int digits) {
    /* we create a format :
        %% : %  the first % is to escape the second %
        0  : 0  zero character
        %d :    how many '0' we want (specified by digits)
        d  : d  the number to format
    */
    String format = String.format("%%0%dd", digits);
    return String.format(format, n);
  }

  public static void main(String[] args) throws Exception{
    System.out.println(NumberUtils.formatLong(123456L, 10));
    // output : 0000123456
  }
}

java.text.MessageFormat can be used to pad a number and then build complex string.
import java.text.MessageFormat;

public class PaddingZeroUsingMessageFormatTest {
  public static void main(String[] args) {
    for (int i=90;i<110;i++) {
      System.out.println(MessageFormat.format("{0}_{1,number,000}", "Counting", i));
    }
    /* output
     * Counting_090
     * Counting_091
     * Counting_092
     * Counting_093
     * Counting_094
     * Counting_095
     * Counting_096
     * Counting_097
     * Counting_098
     * Counting_099
     * Counting_100
     * Counting_101
     * Counting_102
     * ...
     */
    }
}
Or use Apache Commons StringUtils
String paddedString = org.apache.commons.lang.StringUtils.leftPad("123456", 10, "0"); //  0000123456
jdk1.2+
Using DecimalFormat.format()
import java.util.Arrays;
import java.text.DecimalFormat;

public class NumberUtils {
  private NumberUtils() {}

  public static String formatLong(long n, int digits) {
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
    return df.format(n);
  }

  public static void main(String[] args) throws Exception{
    System.out.println(NumberUtils.formatLong(123456L, 10));
    // output : 0000123456
  }
}

pre-jdk1.1
public class DemoNumber {
  public static void main(String args[]) {
    long n = 123456;
    String mask = "00000000000";
    String ds = Long.toString(n);  // double to string
    String z = mask.substring(0 , mask.length() - ds.length()) + ds;
    System.out.println(z);
    // output : 0000123456
  }
}

mail_outline
Send comment, question or suggestion to howto@rgagnon.com