本文介绍了如何从货币代码中获取NumberFormat实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得与ISO 4217货币代码相对应的 NumberFormat (或 DecimalFormat )实例(例如EUR或USD)为了正确格式化价格?

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?

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

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


推荐答案

我不是我正确地理解了这一点,但你可以尝试这样的事情:

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));
    }   
}

输出:

1,234.23

请注意我设置了最大分数位数,未触及最大小数位数:

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

这篇关于如何从货币代码中获取NumberFormat实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-20 23:00