$100 #2 - 100.5 -> $100.50 #3 - 100.41 -> $10-6ren">
gpt4 book ai didi

java - 如何使用 Java 的 DecimalFormat 进行 "smart"货币格式?

转载 作者:bug小助手 更新时间:2023-10-28 10:44:13 26 4
gpt4 key购买 nike

我想使用 Java 的 DecimalFormat 来像这样格式化 double :

#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41

到目前为止,我能想到的最好的是:

new DecimalFormat("'$'0.##");

但这不适用于案例 #2,而是输出“$100.5”

编辑:

很多这些答案只考虑案例 #2 和 #3,并没有意识到他们的解决方案会导致 #1 将 100 格式化为“$100.00”,而不仅仅是“$100”。

最佳答案

一定要使用DecimalFormat吗?

如果没有,看起来以下应该可以工作:

String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
//Handle the weird exception of formatting whole dollar amounts with no decimal
currencyString = currencyString.replaceAll("\\.00", "");

关于java - 如何使用 Java 的 DecimalFormat 进行 "smart"货币格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5033404/

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