Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Currency to Locale Mapping Possible?

Tags:

I have a value stored in a DB correlating to a monetary amount, say 10.0. I also have access to the Currency/CurrencyCode. How can I use NumberFormat/DecimalFormat/(other?) to format when I don't know the Locale? According to the docs it will pick a default locale which won't work with a foreign Currency.

like image 360
Carlos S Avatar asked Apr 16 '09 22:04

Carlos S


People also ask

How can I get currency from locale?

The getSymbol() method is used to get the symbol of a given currency for the default DISPLAY locale. For example, for the US Dollar, the symbol is "$" if the default locale is the US, while for other locales it may be "US$". If no symbol can be determined, the ISO 4217 currency code is returned.

How do you format currencies in Java?

Java provides an automated way for formatting currencies depending on the locale. getCurrencyInstance() is a static method of the NumberFormat class that returns the currency format for the specified locale. Note: A Locale in Java represents a specific geographical, political, or cultural region.


1 Answers

JasonTrue is correct, but you can override the currency of the NumberFormat's locale:

NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale); //the user may have selected a different currency than the default for their locale Currency currency = Currency.getInstance("GBP"); numberFormat.setCurrency(currency); numberFormat.format(amount); 
like image 62
user761574 Avatar answered Sep 21 '22 15:09

user761574