Java Data Type How to - Add leading zeros to a number








Question

We would like to know how to add leading zeros to a number.

Answer

import java.text.DecimalFormat;
import java.text.NumberFormat;
//  w ww. j av  a  2s.  co  m
public class Main {
  public static void main(String[] args) {
    int areaCode = 123;
    int exchangeCode = 456;

    NumberFormat nf3 = new DecimalFormat("0000");

    System.out.println(nf3.format(areaCode) + "-" + nf3.format(exchangeCode));
  }

}