Java Reference
In-Depth Information
Outputting Amounts of Money
Using the class MoneyFormat, you can output an amount of money correctly formatted. To
do so, proceed as follows:
Place the following near the start of the file containing your program:
import java.text.NumberFormat;
In your program code, create an object of the class NumberFormat as follows:
NumberFormat FormatterObject =
NumberFormat.getCurrencyInstance();
When outputting numbers for amounts of money, change the number to a value of type
String using the method FormatterObject.format , as illustrated in what follows:
double moneyAmount = 9.99;
System.out.println(FormatterObject.format(moneyAmount));
The string produced by invocations such as FormatterObject.format(moneyAmount)
adds the dollar sign and ensures that there are exactly two digits after the decimal point.
(This is assuming the U.S. dollar is the default currency.)
The numbers formatted in this way may be of type double , int , or long . You may use
any (nonkeyword) identifier in place of FormatterObject . A complete example is given
in Display 2.3.
The above always outputs the money amount in the default currency, which is typically the
local currency. You can specify the country whose currency you want. See the text for details.
This kind of statement is called an import statement . In this example, the import
statement tells Java to look in the package java.text to find the definition of the class
NumberFormat .
If you wanted to import all the classes in the java.text package, you would use
import
statement
import java.text .*;
Then you can use any class in the java.text package.
You don't lose any efficiency in importing the entire package instead of importing
only the classes you use. However, many programmers find that it is an aid to documen-
tation if they import only the classes they use, which is what we will do in this topic.
In Display 2.3, we also used the class Locale , which is in the java.util package.
So we also included the following import statement:
java.util
import java.util.Locale;
Search WWH ::




Custom Search