gpt4 book ai didi

java - 修改 NumberFormat.getCurrencyInstance() 返回的 NumberFormat

转载 作者:行者123 更新时间:2023-11-29 03:39:05 30 4
gpt4 key购买 nike

我在使用 Java 格式化货币时遇到问题。我正在尝试格式化要打印为货币的数字,所有小数点都对齐:

£  1.23
£ 12.34
£123.45

调用 NumberFormat.getCurrencyInstance().format(n) 返回格式化字符串,但所有数字都是左对齐的,产生如下输出:

£1.23
£12.34
£123.45

丑陋的。我读过this post它提供了一个使用 DecimalFormat 的解决方案,作为权宜之计,我正在使用 DecimalFormat 格式化我的数字并在稍后添加货币符号,但我想知道是否有人知道一种更简洁的方法来完成一样吗?

希望一切都清楚,在此先感谢您的帮助!

最佳答案

你可以这样做:

String currencySymbol = Currency.getInstance(Locale.getDefault()).getSymbol();
System.out.printf("%s%8.2f\n", currencySymbol, 1.23);
System.out.printf("%s%8.2f\n", currencySymbol, 12.34);
System.out.printf("%s%8.2f\n", currencySymbol, 123.45);

注意:这仅适用于符号出现在金额之前的货币。

还要注意以下事实:doubles are not suitable for representing currency .

关于java - 修改 NumberFormat.getCurrencyInstance() 返回的 NumberFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14023365/

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