gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:32:33 25 4
gpt4 key购买 nike

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

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.

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...

最佳答案

我不确定我是否理解正确,但您可以尝试类似的方法:

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不触及最大小数位数:

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.

关于java - 如何从货币代码中获取 NumberFormat 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9777689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com