Formatting Numbers in Java using DecimalFormat Custom Format Code - Expanded Steps.

By Lon Hosford

This demonstrates formatting numbers using custom formatting codes. The program steps are expanded so each step has its own 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 String and assign a formatting code.
        --------------------------------------------------------*/
        String format = "0.00#";
 
        /*--------------------------------------------------------
        Define a DecimalFormat object named rounder
        and run the DecimalFormat class constructor
        method passing the format code as the argument
        --------------------------------------------------------*/
        DecimalFormat rounder = new DecimalFormat(format);
 
        /*--------------------------------------------------------
        Define a double named answer as the
        division of the two integers.
        --------------------------------------------------------*/
        double answer = a/b;

        /*--------------------------------------------------------
        Define a String by running the
        DecimalFormat object rounder's format
        method takes a double as an argument
        and returns a String formatted
        --------------------------------------------------------*/
        String roundedAnswer = rounder.format(answer);

        /*--------------------------------------------------------
        Display the formatted number.
        --------------------------------------------------------*/
        System.out.println("The total payment will be: $"+roundedAnswer);

    }
}