How do I format a number with leading zeros?

This example give you an example using java.text.DecimalFormat class to add leading zeros to a number. For a another method you can read the see the earlier example on How do I add leading zeros to a number?.

package org.kodejava.example.lang;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class NumberFormatLeadingZerosExample {
    public static void main(String[] args) {
    NumberFormat formatter = new DecimalFormat("0000000");
    String number = formatter.format(2500);

    System.out.println("Number with lading zeros: " + number);

The result of code snippet above:

Number with lading zeros: 0002500

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply