Archive for the 'Java' Category

Java formatting a number with leading zeroes

Friday, July 17th, 2009

Recently, I had a Java project that needed to encode a set of numbers and I needed a fixed number of digits used for each number. I found the DecimalFormat class a good solution for my needs.

Here is a snippet of code to show a simple way to format a number with a fixed number of digits.

import java.text.DecimalFormat;

class TestEncoder
{
        public static void main(String[] args)
        {
                // This program expects one integer 
                // argument and places it in the num1 
                // variable. This program is not very 
                // robust as to watch for no arguments
                // or to check if the argument is not 
                // an integer.
                String num1 = args[0];
                String output;

                // This creates the Decimal Format instance 
                // and assigns the formatting that we want 
                // to use, in this case three characters .
                DecimalFormat dfmt = 
                             new DecimalFormat("000");

                // This does the work of formatting the number
                // passed in on the command line to be at least
                // three digits. 
                output = dfmt.format(new Integer(num1));
               
                // This just displays the results of the 
                // dfmt.format(new Integer(num1)) command.
                System.out.println("Output: " + output);
}
}

The Decimal format allows for many more formatting options for numbers.

Make sure to look a the API docs for the version of Java that you are using:
http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html

Tags: ,