Formatting with the java.text Package
The java.text package
includes, among other things, a set of classes designed for generating and
parsing string representations of objects. In this section, we’ll talk
about three classes: NumberFormat, ChoiceFormat, and
MessageFormat. Chapter 11 describes the DateFormat class. As we said earlier, the
classes of the java.text package
overlap to a large degree with the capabilities of the Scanner and printf-style Formatter. Despite these new features, a number
of areas in the parsing of currencies, dates, and times can only be
handled with the java.text
package.
The NumberFormat class can be
used to format and parse currency, percentages, or plain old numbers.
NumberFormat is an abstract class, but
it has several useful factory methods that produce formatters for
different types of numbers. For example, to format or parse currency
strings, use getCurrencyInstance()
:
doublesalary=1234.56;Stringhere=// $1,234.56NumberFormat.getCurrencyInstance().format(salary);Stringitaly=// L 1.234,56NumberFormat.getCurrencyInstance(Locale.ITALY).format(salary);
The first statement generates an American salary, with a dollar
sign, a comma to separate thousands, and a period as a decimal point. The
second statement presents the same string in Italian, with a lire sign, a
period to separate thousands, and a comma as a decimal point. Remember
that NumberFormat worries about format only; it doesn’t attempt to do currency conversion. We can go the other ...