Get the currency format for a country that does not have a Locale constant

前端 未结 6 1114
醉梦人生
醉梦人生 2020-12-29 02:44

I want to get the currency format of India, so I need a Locale object for India. But there exists only few a countries that have a Locale constant

6条回答
  •  难免孤独
    2020-12-29 03:14

    Here is an utility method to have the symbol, whatever is your locale

        public class Utils {
    
            public static SortedMap currencyLocaleMap;
    
            static {
                currencyLocaleMap = new TreeMap(new Comparator() {
                    @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 getCurrencySymbol(String currencyCode) {
                Currency currency = Currency.getInstance(currencyCode);
                return currency.getSymbol(currencyLocaleMap.get(currency));
            }
    
           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);
        }
    
    
        }
    

提交回复
热议问题