Java 如何从货币代码中获取 NumberFormat 实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9777689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:33:15  来源:igfitidea点击:

How to get NumberFormat instance from currency code?

java

提问by Adil Hussain

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 prices correctly?

如何获取与 ISO 4217 货币代码(例如“EUR”或“USD”)对应的NumberFormat(或DecimalFormat)实例以正确格式化价格?

Note 1:The problem I'm having is that the NumberFormat/DecimalFormatclasses have a getCurrencyInstance(Locale locale)method but I can't figure out how to get to a Localeobject from an ISO 4217 currency code.

Note 2:There is also a java.util.Currencyclass which has a getInstance(String currencyCode)method (returning the Currencyinstance for a given ISO 4217 currency code) but again I can't figure out how to get from a Currencyobject to a NumberFormatinstance...

注 1:我遇到的问题是NumberFormat/DecimalFormat类有一个 getCurrencyInstance(Locale locale)方法,但我不知道如何Locale从 ISO 4217 货币代码获取对象。

注 2:还有一个java.util.Currency类有一个getInstance(String currencyCode)方法(返回Currency给定 ISO 4217 货币代码的实例),但我又不知道如何从一个Currency对象到一个NumberFormat实例......

采纳答案by esaj

I'm not sure I understood this correctly, but you could try something like:

我不确定我是否正确理解了这一点,但您可以尝试以下操作:

public class CurrencyTest
{
    @Test
    public void testGetNumberFormatForCurrencyCode()
    {
        NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(2);
        Currency currency = Currency.getInstance("USD");
        format.setCurrency(currency);

        System.out.println(format.format(1234.23434));
    }   
}

Output:

输出:

1,234.23

Notice that I set the maximum amount of fractional digits separately, the NumberFormat.setCurrencydoesn't touch the maximum amount of fractional digits:

请注意,我单独设置了小数位数的最大数量,NumberFormat.setCurrency不会触及小数位数的最大数量:

Sets the currency used by this number format when formatting currency values. This does not update the minimum or maximum number of fraction digits used by the number format.

在格式化货币值时设置此数字格式使用的货币。这不会更新数字格式使用的最小或最大小数位数。

回答by Bernard

Try the following method:

尝试以下方法:

private static NumberFormat getNumberFormat(String currencyCode)
{
    Currency currency = Currency.getInstance(currencyCode);

    Locale[] locales = NumberFormat.getAvailableLocales();

    for (Locale locale : locales)
    {
        NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);

        if (numberFormat.getCurrency() == currency)
            return numberFormat;
    }

    return null;
}

回答by Adam

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<Locale> getLocalesFromIso4217(String iso4217code) {
    Collection<Locale> returnValue = new LinkedList<Locale>();
    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 

回答by Spencer Kormos

Locale can be used both to get the standard currency for the Locale and to print anycurrency symbol properly in the locale you specify. These are two distinct operations, and not really related.

区域设置既可用于获取区域设置的标准货币,也可用于在您指定的区域设置中正确打印任何货币符号。这是两个不同的操作,并没有真正相关。

From the Java Internationalization tutorial, you first get an instance of the Currency using either the Locale or the ISO code. Then you can print the symbol using anotherLocale. So if you get the US Currency from the en_US Locale, and call getSymbol() it will print "$". But if you call getSymbol(Locale) with the British Locale, it will print "USD".

Java 国际化教程 中,您首先使用区域设置或 ISO 代码获取货币的实例。然后您可以使用另一个区域设置打印符号。因此,如果您从 en_US Locale 获取美国货币,并调用 getSymbol() 它将打印“$”。但是,如果您使用英国语言​​环境调用 getSymbol(Locale),它将打印“USD”。

So if you don't care what your current user's locale is, and you just care about the currencies, then you can ignore the Locale in all cases.

因此,如果您不关心当前用户的语言环境,而只关心货币,那么在所有情况下都可以忽略语言环境。

If you care about representing the currency symbol correctly based on your current user, then you need to get the Locale of the userspecific to the user's location.

如果你关心正确地表示基于当前用户的货币符号,那么你就需要获得区域设置用户的特定于用户的位置。

回答by Spencer Kormos

For completeness, though I've never used it, you might want to give Joda Moneya try. If it's as good as Joda-Time, it probably is easier and more powerful than the standard JDK stuff.

为了完整起见,虽然我从未使用过它,但您可能想尝试一下Joda Money。如果它和 Joda-Time 一样好,它可能比标准的 JDK 东西更容易和更强大。

回答by Shroud

public class PriceHelper {
    public static String formatPrice(Context context, String currencyCode, 
                                      double price) {
        if (price == 0) {
            return context.getString(R.string.free);
        }
        Currency currency = Currency.getInstance(currencyCode);
        NumberFormat format = NumberFormat.getCurrencyInstance();
        format.setCurrency(currency);
        return format.format(price);
    }
}