A Java DecimalFormat example

Here's a quick example of how to use the Java DecimalFormat class to format float and double numbers for output, such as printing information in a currency format.

The example below creates a simple DecimalFormat that is similar to a U.S. currency format. As you can see from the for loop, it begins printing at 100, and prints decimal numbers up to a value of just over 1,000:

import java.text.*;

public class JavaDecimalFormatExample
  public static void main (String[] args)
    NumberFormat numberFormat = new DecimalFormat("#,###.00");
    for ( double amount=50; amount<1100; amount+=50.5 )
      System.out.println( "" );
      System.out.println( "amount without formatting: " + amount );
      System.out.println( "amount with    formatting: " + numberFormat.format(amount) );

DecimalFormat example output

I won't show all of the output from this DecimalFormat example program here, but I'll show a few lines so you can see the difference between not formatting the output, and applying a simple format like the one shown above:

# lines from the beginning of the output:

amount without formatting: 50.0
amount with    formatting: 50.00

amount without formatting: 100.5
amount with    formatting: 100.50

# lines from the end of the output:

amount without formatting: 959.0
amount with    formatting: 959.00

amount without formatting: 1009.5
amount with    formatting: 1,009.50

amount without formatting: 1060.0
amount with    formatting: 1,060.00

More Java number formatting information

Check out the Java DecimalFormat javadoc for more Java decimal number formatting information, including details about all of the formatting symbols you can use.

Also, check out the NumberFormat javadoc, as the Java NumberFormat class is "the base class for all number formats."