Posted by: dcsaha | May 5, 2011

How do I format a number with leading zeros, in Java?

This is an example using java.text.DecimalFormat class to add leading zeros to a number. The method shown is available before Java 1.5

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 following example shows you how to use the String.format() method to add zero padding to a number. If you just want to print out the result you can use System.out.format(). This method is available since Java 1.5, so If you use a previous version you can use the NumberFormat class shown above.

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

Courtesy: http://www.kodejava.org/examples/174.html

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.