|
|
Locale-Sensitive Data |
Now that you understand in general terms how formatters work, let's look at some specific examples from theAroundTheWorldapplet. Let's start with formatting numbers.Here's the code that
AroundTheWorlduses 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 thenumbersresource bundle. And finally, the code uses the formatter'sformatmethod to format the data into a string which is then used to set the text of the label in the panel.The
NumberFormat.getCurrencyInstancemethod creates aDecimalFormatobject that is set up to format numbers in a way that represents money data in the formatter'sLocale. TheLocaleis specified as a parameter to the factory method. Similary,NumberFormat.getPercentInstancecreates aDecimalFormatobject that is set up to format numbers that represent percentages.NumberFormat.getNumberInstancecreates aDecimalFormatobject 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
NumberFormatclass is unapparent from this example. Here's a demo program from Taligent that you can use to see whatNumberFormatcan do.
|
|
Locale-Sensitive Data |