如何将ISO4217货币代码提供给NumberFormat?

Aut*_*M8R 5 string android iso currency number-formatting

我想避免使用Locale,而是使用货币代码(ISO 4217,如"USD").我理解如何使用货币代码设置Currency类,但是,我如何将此货币合并为一个NumberFormat以将双倍格式化为所述货币?

我分别理解NumberFormat和Currency,但我怎样才能将这些格式组合成双倍的真实货币字符串,例如4.00 - > $ 4.00?我必须使用NumberFormat,因为我在这个例子中删除小数位以产生诸如$ 4的整个货币数字.

谢谢你的帮助,瑞恩

编辑:答案,.setCurrency,这是我在NumberFormat中没有注意到的,doh!我过于专注于使用Currency构建NumberFormat,但我一直在努力,因为你只能从Locale构造.希望我早些想到这个.谢谢!下次我将阅读更接近的方法列表.我KNEW NumberFormat HAD支持Currency类,只有这样才能使用Currency.

Sea*_*wen 4

这应该可以让您以给定货币显示最接近的整数货币单位的金额。我没有测试过,但认为它是 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);
Run Code Online (Sandbox Code Playgroud)