【问题标题】:How can I feed a ISO4217 Currency Code to a NumberFormat?如何将 ISO4217 货币代码提供给 NumberFormat?
【发布时间】:2012-10-22 06:43:57
【问题描述】:

我想避免使用区域设置,而是使用货币代码(ISO 4217,如“USD”)。我了解如何使用货币代码设置 Currency 类,但是,我如何将此 Currency 合并到一个 NumberFormat 中以将双精度设置为所述货币?

我分别了解 NumberFormat 和 Currency,但是如何将它们组合起来以将双精度值格式化为真正的货币字符串,例如 4.00 -> $4.00?我必须使用 NumberFormat,因为我会去掉小数位以生成整个货币数字,例如本例中的 $4。

感谢您的帮助, 瑞恩

编辑:回答,.setCurrency,这是我在 NumberFormat 中没有注意到的,呵呵!我太专注于用货币构造 NumberFormat,但我很挣扎,因为你只能从 Locale 构造。希望我早点想到这一点。谢谢!下次我会更仔细地阅读列出的方法。我知道 NumberFormat 必须支持 Currency 类,只有以这种方式使用 Currency 才有意义。

【问题讨论】:

  • 请不要评论我使用 Doubles 作为货币,我不需要精确。谢谢。

标签: android string currency iso number-formatting


【解决方案1】:

这应该让您以给定货币显示最接近的完整货币单位的金额。我还没有测试过,但我认为它 95% 是正确的。

double amount = ...;
String currencyCode = ...;
Currency currency = Currency.getInstance(currencyCode);
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMaximumFractionDigits(0);
format.setCurrency(currency);
String formattedAmount = format.format(amount);

【讨论】:

    【解决方案2】:

    您是否尝试过以下代码:

        NumberFormat nf = NumberFormat.getCurrencyInstance();
        String currencyCode = "USD";
        nf.setCurrency(Currency.getInstance(currencyCode));
        double currencyAmmount = 4.00;
        String formattedValue= nf.format(currencyAmmount);
    

    从上面的代码中我得到了$4.00,我认为这是你所期望的。

    我想这里最重要的是使用NumberFormat.getCurrencyInstance() 而不是NumberFormat.getInstance()

    【讨论】:

    • 谢谢,另一个有效的答案。你只是错过了我正在删除小数的事实。
    猜你喜欢
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2019-05-14
    相关资源
    最近更新 更多