Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 12 Localization

The NumberFormat Class

The NumberFormat class provides support for processing numbers in a locale-sensitive manner. For example, depending on the locale, how thousands are separated, the punctuation characters used for separating them, printing an amount as a currency value, etc. are different, and the NumberFormat class provides this functionality.

The NumberFormat class provides methods to format or parse numbers. Here “formatting” means converting a numeric value to a string value in a culture-sensitive way; similarly, “parsing” means converting a number back to numeric form. For example, if you want to print the long constant value 10_000_000L into ten million in German locale, you format this value by passing it to the format() method in the NumberFormat class, and this method will return the String “10.000.000” (note the use of dot as a separation character for thousands). Now, if you read the

input value 10 million in German locale to convert that value to a long value to use it in the program, you can pass the string to the parse() method. Listing 12-8 shows the steps to perform these conversions.

Listing 12-8.  FormatNumber.java

import java.util.*; import java.text.*;

// class to demonstrate how to format or parse numbers for a particular locale class FormatNumber {

public static void main(String []args) { long tenMillion = 10_000_000L;

// first print ten million in German locale

NumberFormat germanFormat = NumberFormat.getInstance(Locale.GERMANY); String localizedTenMillion = germanFormat.format(tenMillion);

System.out.println("Ten million in German locale is " + localizedTenMillion);

// now, scan the value ten million given in German locale try {

Number parsedAmount = germanFormat.parse(localizedTenMillion); if(tenMillion == parsedAmount.longValue()) {

System.out.println("Successfully parsed the number for the locale");

}

}

catch (ParseException pe) {

System.err.println("Error: Cannot parse the number for the locale");

}

}

}

It prints the following:

Ten million in German locale is 10.000.000

Successfully parsed the number value back to Number value based on the locale

As you can see, the value 10 million is printed in this format in German locale: 10.000.000. To parse such a number in a given locale, you can use the NumberFormat’s parse() method, which returns a Number if the parsing is successful—or else the method throws a checked exception, ParseException.

Note that the parse() method is different from the format() method. The parse() method is meant for reading numbers provided as String and trying to convert it to Number. The format() method is used for printing the values according to the values set in the NumberFormat object. Listing 12-9 illustrates the difference between the two.

377

Chapter 12 Localization

Listing 12-9.  FractionDigits.java

import java.util.*; import java.text.*;

public class FractionDigits {

public static void main(String[] args) throws ParseException { String[] numbers = {"1.222", "0.12345F"};

double[] doubles = {1.222, 0.12345F};

NumberFormat numberFormat = NumberFormat.getInstance(); numberFormat.setMaximumFractionDigits(2); System.out.println("Using format method: ");

for(double val : doubles) { System.out.println(numberFormat.format(val));

}

System.out.println("Using parse method: "); for(String number : numbers) {

System.out.println(numberFormat.parse(number));

}

}

}

It prints the following:

Using format method: 1.22 0.12

Using parse method: 1.222 0.12345

The parse() method reads the values and converts it to Number if it succeeds. So, it does not use the maximum fraction digits set using setMaximumFractionDigits(); however, if it were to use the format() method, which is meant for printing numbers, it would use this maximum fraction digits limit set, which explains the difference between the outputs.

Important methods in the NumberFormat class are listed in Table 12-3. The static methods that start with the “get” prefix and end with the “Instance” suffix—such as getCurrencyInstance()—are factory methods supported by this class.

Table 12-3.  Important Methods in the NumberFormat Class

Method

Short Description

String format(double number)

String format(long number)

Formats the number according to the NumberFormat’s locale. The first two overloaded methods use an implicit StringBuffer, whereas the last two use an explicit StringBuffer to build the String.

Number parse(String source)

Parses the number from the given String. It returns a Long or

 

Double instance depending on the value of the number given

 

in source. Throws a ParseException if the parse fails.

 

 

 

(continued )

378

 

Chapter 12 Localization

Table 12-3.(continued )

 

 

 

Method

Short Description

static Locale[] getAvailableLocales()

Returns the list of the locales supported by the Java runtime for

 

number formatting.

static NumberFormat getInstance()

Factory method that returns a NumberFormat object for the

 

default locale.

Currency getCurrency()

Returns the currency instance used by this NumberFormat object.

static NumberFormat getCurrencyInstance()

Returns the instance of NumberFormat suitable for currency

 

formatting purposes; an overloaded version of this method

 

takes a Locale as an argument.

static NumberFormat getIntegerInstance()

Returns the instance of NumberFormat suitable for use for

 

formatting integer numbers; an overloaded version of this

 

method takes a Locale as an argument.

static NumberFormat getPercentInstance()

Returns the instance of NumberFormat suitable for use for

 

formatting for percentages; an overloaded version of this

 

method takes a Locale as an argument.

 

 

The NumberFormat class supports printing currency values. You can use its getCurrencyInstance() method, which returns a Currency object. Listing 12-10 illustrates how to make use of this method for printing the value 10 million in four different locales (without performing exchange rate conversions).

Listing 12-10.  LocalizedCurrency.java

import java.util.*; import java.text.*;

// Ilustrates how to use NumberFormat class to get Currency instance class LocalizedCurrency {

public static void main(String []args) {

long tenMillion = 10000000L; // this is ten million Locale [] locales =

{ Locale.CANADA, Locale.FRANCE, Locale.GERMANY, Locale.TAIWAN };

//for each of the four locales,

//print the currency amount as it looks in that locale for(Locale locale : locales) {

System.out.println("Ten million in " + locale.getDisplayName() + " is " + NumberFormat.getCurrencyInstance(locale).format(tenMillion));

}

}

}

It prints:

Ten million in English (Canada) is $10,000,000.00 Ten million in French (France) is 10 000 000,00 € Ten million in German (Germany) is 10.000.000,00 € Ten million in Chinese (Taiwan) is NT$10,000,000.00

379

Chapter 12 LoCaLization

As you can see, by using the NumberFormat object returned from getCurrencyInstance(Locale), you can format numbers to print them as currency values for a locale. You can also use the Currency class independently of the NumberFormat class, as we’ll discuss now.

The Currency Class

Table 12-4 lists important methods the Currency class.

Table 12-4. Important Methods in the Currency Class

 

 

 

Method

Short Description

int getNumericCode()

Returns ISO 4217 numeric code for the currency.

int getDefaultFractionDigits()

Returns the default number of digits used with the

 

currency, such as zero for the Japanese Yen and two

 

for the US Dollar.

String getDisplayName()

Returns the readable description of the Currency for

 

the underlying locale, for example, US Dollar.

String getDisplayName(Locale)

Returns the readable description of the Currency for

 

the given locale.

static Currency getInstance(String currencyCode)

Returns the Currency object corresponding to the

 

given currency code.

static Currency getInstance(Locale locale)

static Set < Currency > getAvailableCurrencies()

String getSymbol()

String getSymbol(Locale)

String getCurrencyCode()

Returns the Currency object corresponding to the given Locale object.

Get the list of Currency instances available in the JDK.

Returns the currency symbol, if any; otherwise, returns the currency code.

Returns the currency symbol for the given Locale object.

Returns the currency code (ISO 4217) for locale of the Currency instance.

Listing 12-11 shows how to make use of few of these methods listed in Table 12-4.

Listing 12-11. CurrencyDetails.java

import java.util.*;

// Get the currency details of the default locale (en_US locale) class CurrencyDetails {

public static void main(String []args) { Locale locale = Locale.getDefault();

Currency currencyInstance = Currency.getInstance(locale); System.out.println(" The currency code for locale " + locale

+ " is: " + currencyInstance.getCurrencyCode()

380

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]