如何从货币代码中获取NumberFormat实例? [英] How to get NumberFormat instance from currency code?

查看:167
本文介绍了如何从货币代码中获取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?


注1:问题我我有的是 NumberFormat / DecimalFormat 类有一个
getCurrencyInstance(区域设置区域设置)方法,但我无法弄清楚
如何从ISO 4217货币代码获取区域设置对象。

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

注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

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

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


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

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆