Java Reference
In-Depth Information
String format (
double
number)
Returns a string containing the specified number formatted according to this
object's pattern.
static
NumberFormat getCurrencyInstance()
Returns a NumberFormat object that represents a currency format for the
current locale.
static
NumberFormat getPercentInstance()
Returns a NumberFormat object that represents a percentage format for the
current locale.
FIGURE 3.6
Some methods of the
NumberFormat
class
Two of the methods in the
NumberFormat
class,
getCurrencyInstance
and
getPercentInstance
, return an object that is used to format numbers. The
getCurrencyInstance
method returns a formatter for monetary values, and
the
getPercentInstance
method returns an object that formats a percentage.
The
format
method is invoked through a formatter object and returns a
String
that contains the number formatted in the appropriate manner.
The
Purchase
program shown in Listing 3.4 uses both types of formatters. It
reads in a sales transaction and computes the final price, including tax.
LISTING 3.4
//********************************************************************
// Purchase.java Author: Lewis/Loftus
//
// Demonstrates the use of the NumberFormat class to format output.
//********************************************************************
import
java.util.Scanner;
import
java.text.NumberFormat;
public class
Purchase
{
//-----------------------------------------------------------------
// Calculates the final price of a purchased item using values
// entered by the user.
//-----------------------------------------------------------------
public static void
main (String[] args)
Search WWH ::
Custom Search