Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet210/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   206   207   208   209   210   211   212   213   ...   245
Bog'liq
Java 17 Recipes

 How It Works
You use a NumberFormat instance to format currency values. You should explicitly call the 
getCurrencyInstance() method to create a formatter for currencies.
NumberFormat nf = NumberFormat.getCurrencyInstance();
The previous formatter uses your default locale’s preferences for formatting numbers 
as currency values. Also, it uses a currency symbol associated with the locale’s region. 
However, one common use case involves formatting a value for a different region’s 
currency.
Use the setCurrency() method to explicitly set the currency in the number 
formatter.
nf.setCurrency(aCurrencyInstance); // requires a Currency instance
Note that the java.util.Currency final class is a factory. It allows you to create 
currency objects in two ways.
• Currency.getInstance(Locale locale)
• Currency.getInstance(String currencyCode)
Chapter 11 UniCode, internationalization, and CUrrenCy Codes 


415
The first getInstance call uses a Locale instance to retrieve a currency object. The 
Java platform associates a default currency with the locale’s region. In this case, the 
default currency currently associated with the United States is the US dollar.
Currency c1 = Currency.getInstance(Locale.US);
The second getInstance call uses a valid ISO 4217 currency code. The currency 
code for the US dollar is USD.
Currency c2 = Currency.getInstance("USD");
Once you have a currency instance, you simply have to use that instance in your 
formatter.
nf.setCurrency(c2);
This formatter is configured to use the default locale’s number format symbols and 
patterns to format the number value, but it displays the targeted currency code as part 
of the displayable text. This allows you to mix the default number format patterns with 
other currency codes.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   206   207   208   209   210   211   212   213   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling