Formatting Numbers in Java using DecimalFormat Custom Format Code - Condensed One Step

By Lon Hosford

This demonstrates formatting numbers using custom formatting codes. The program steps are condensed so all steps are on one line of code. Get formatting codes at http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html.

 

 

/*--------------------------------------------------------
Include the DecimalFormat class from the Java API
Also could be done as
import java.text.DecimalFormat;
--------------------------------------------------------*/
import java.text.*;
 

public class DecimalFormatter
{
    public static void main(String[] args)
    {
 
        /*--------------------------------------------------------
        Define an integer and initialize to 500.
        --------------------------------------------------------*/
        int a = 500;
        /*--------------------------------------------------------
        Define an integer and initialize to 3.
        --------------------------------------------------------*/
        int b = 3;
 
        /*--------------------------------------------------------
        Define a double named answer as the
        division of the two integers.
        --------------------------------------------------------*/
        double answer = a/b;

        /*--------------------------------------------------------
        Define an anonymous DecimalFormat object
        and run the DecimalFormat class constructor
        method passing the format code  "0.00#" as the argument
        and simultaneously calling the format method and
        passing the double variable answer.
 
        Then display the formatted number.
        --------------------------------------------------------*/
        System.out.println("The total payment will be: $" + new DecimalFormat("0.00#").format(answer));
    }
}