Proper currency format when not displaying the native currency of a culture

别等时光非礼了梦想. 提交于 2019-11-27 11:58:55
cletus

There's no absolute rules here but a couple of guiding principles:

  1. Try and use the number format for that locale (eg 1,000.00 in the US would be displayed as 1'000,00 in Germany);
  2. Remember that different currencies can use the same symbol (eg $ is used by Australian and US Dollars) and that there are many currency symbols;
  3. If your site is "single" currency then just use the correct symbol for that currency. By this I mean sites like Amazon, travel sites, shopping sites and so on. These sites are single currency in the sense they are one currency at a time. They won't be displaying Malaysian Ringits and Singapore Dollars at the same time, for example; and
  4. If your site is multi-currency then don't use the symbol at all: use the international standard three letter currency code as defined by ISO 4217 currency names and code elements. Sites like xe.com fit into the category.

If you always want to display the symbol, here is an utility class:

public class Utils {

    public static SortedMap<Currency, Locale> currencyLocaleMap;

    static {
        currencyLocaleMap = new TreeMap<Currency, Locale>(new Comparator<Currency>() {
            @Override
            public int compare(Currency c1, Currency c2) {
                return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
            }
        });

        for (Locale locale : Locale.getAvailableLocales()) {
            try {
                Currency currency = Currency.getInstance(locale);
                currencyLocaleMap.put(currency, locale);
            }
            catch (Exception e) {
            }
        }
    }


    public static String  getAmountAsFormattedString(Double amount, Double decimals, String currencyCode) {
        Currency currency = Currency.getInstance(currencyCode);
        double doubleBalance = 0.00;
        if (amount != null) {
            doubleBalance = ((Double) amount) / (Math.pow(10.0, decimals));
        }
        NumberFormat numberFormat = NumberFormat.getCurrencyInstance(currencyLocaleMap.get(currency));
        return numberFormat.format(doubleBalance);
    }

    public static String getCurrencySymbol(String currencyCode) {
        Currency currency = Currency.getInstance(currencyCode);
        return currency.getSymbol(currencyLocaleMap.get(currency));
    }


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!