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 specific the 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
  }
}

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

blog comments powered by Disqus