Java Cookbook
Use a non-default currency
Problem:
You want to use a currency other than the default for the region.
Solution:
We can specify a currency separate from a region. This will give us a numeric format that is appropriate to the locale, but use a currency code for the specified locale.
//Get a locale.
Locale italian = new Locale("it","IT");
//Get a currency instance
Currency c = Currency.getInstance("JPY");
//Get a currency instance
NumberFormat nf = NumberFormat.getCurrencyInstance(italian);
nf.setCurrency(c);
//format and output. Notice the rounding is not limited to two place on the output. Rounding
//is now governed by the locale. Also notice we now use the ISO code istead of a symbol
String f = nf.format(123456.789);
System.out.println(f);
//Parse the value. We must handle the potential ParseException
//Notice that we can not handle the '¥' mark in the parse
try {
System.out.println(nf.parse("JPY 123.456,79"));
} catch (ParseException e) {
e.printStackTrace();
}
The output:
JPY 123.456,79
123456.79
If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.
This site is ad supported. I hope you find something among our sponsors worth clicking. ;)
i18n search