How to get NumberFormat instance from currency code?

前端 未结 6 1352
無奈伤痛
無奈伤痛 2020-12-15 05:25

How can I get a NumberFormat (or DecimalFormat) instance corresponding to an ISO 4217 currency code (such as \"EUR\" or \"USD\") in order to format

6条回答
  •  心在旅途
    2020-12-15 05:36

    The mapping is sometimes one to many... Like the euro is used in many countries (locales)...

    Just because the currency code is the same the format might be different as this example shows:

    private static Collection getLocalesFromIso4217(String iso4217code) {
        Collection returnValue = new LinkedList();
        for (Locale locale : NumberFormat.getAvailableLocales()) {
            String code = NumberFormat.getCurrencyInstance(locale).
            getCurrency().getCurrencyCode();
            if (iso4217code.equals(code)) {
                returnValue.add(locale);
            }
        }  
        return returnValue;
    }
    
    public static void main(String[] args) {
        System.out.println(getLocalesFromIso4217("USD"));
        System.out.println(getLocalesFromIso4217("EUR"));
        for (Locale locale : getLocalesFromIso4217("EUR")) {
            System.out.println(locale + "=>" + NumberFormat.getCurrencyInstance(locale).format(1234));
        }
    }
    

    Output

    [en_US, es_US, es_EC, es_PR]
    [pt_PT, el_CY, fi_FI, en_MT, sl_SI, ga_IE, fr_BE, es_ES, de_AT, nl_NL, el_GR, it_IT, en_IE, fr_LU, nl_BE, ca_ES, sr_ME, mt_MT, fr_FR, de_DE, de_LU]
    
    pt_PT=>1.234,00 €
    el_CY=>€1.234,00
    fi_FI=>1 234,00 €
    en_MT=>€1,234.00
    sl_SI=>€ 1.234
    ga_IE=>€1,234.00
    fr_BE=>1.234,00 €
    es_ES=>1.234,00 €
    de_AT=>€ 1.234,00
    nl_NL=>€ 1.234,00
    el_GR=>1.234,00 €
    it_IT=>€ 1.234,00
    en_IE=>€1,234.00
    fr_LU=>1 234,00 €
    nl_BE=>1.234,00 €
    ca_ES=>€ 1.234,00
    sr_ME=>€ 1.234,00
    mt_MT=>€1,234.00
    fr_FR=>1 234,00 €
    de_DE=>1.234,00 €
    de_LU=>1.234,00 €
    

提交回复
热议问题