Formatting Numbers in Java using NumberFormat and Predefined Formatting by Locale

By Lon Hosford

This shows how to format numbers using predefined formats by international locales. The lines of code are condensed into one step. For more information on the Locals see Field Summary at  http://java.sun.com/j2se/1.4.2/docs/api/java/util/Locale.html 

 

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

 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;
 
        /*--------------------------------------------------------
        Display the answer in US number format format       
        --------------------------------------------------------*/
        System.out.println("The total payment will be: $"
            + NumberFormat.getNumberInstance(Locale.US).format(answer));
 
        /*--------------------------------------------------------
        Display the answer in US currency format
        --------------------------------------------------------*/
        System.out.println("The total payment will be: "
            + NumberFormat.getCurrencyInstance(Locale.US).format(answer));      }
}