![]() ![]() ![]() ![]() |
Locale-Sensitive Data |
Now that you understand in general terms how formatters work, let's look at some specific examples from theAroundTheWorld
applet. Let's start with formatting numbers.Here's the code that
AroundTheWorld
uses to format it's three numbers: the GDP, the population, and the literacy rate for the three locales:For each number, the code gets a formatter using one of the factory methods provided bygdpFormatter = NumberFormat.getCurrencyInstance(currentLocale); gdp = (Double) numbers.getObject("GDP"); gdpValue.setText(gdpFormatter.format(gdp)); . . . populationFormatter = NumberFormat.getNumberInstance(currentLocale); population = (Integer) numbers.getObject("Population"); populationValue.setText(populationFormatter.format(population)); . . . literacyFormatter = NumberFormat.getPercentInstance(currentLocale); literacy = (Double) numbers.getObject("Literacy"); literacyValue.setText(literacyFormatter.format(literacy));NumberFormat
. Depending on the data to be formatted, the code gets a currency formatter, a percent formatter, or a formatter for general-purpose decimal numbers. Next, the code gets the data to be formatted from thenumbers
resource bundle. And finally, the code uses the formatter'sformat
method to format the data into a string which is then used to set the text of the label in the panel.The
NumberFormat.getCurrencyInstance
method creates aDecimalFormat
object that is set up to format numbers in a way that represents money data in the formatter'sLocale
. TheLocale
is specified as a parameter to the factory method. Similary,NumberFormat.getPercentInstance
creates aDecimalFormat
object that is set up to format numbers that represent percentages.NumberFormat.getNumberInstance
creates aDecimalFormat
object that formats regular decimal numbers.This small example illustrates how most programmers will use the number formatters: Most programmers will use one of the already-initialized formatters provided by the JDK. The initialization of the number formatters is hidden and consequently, the full capability of the
NumberFormat
class is unapparent from this example. Here's a demo program from Taligent that you can use to see whatNumberFormat
can do.
![]() ![]() ![]() ![]() |
Locale-Sensitive Data |