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

我想使用 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/

相关文章:

java - 日期和时间格式取决于区域设置

c - intptr_t 和 uintptr_t 的字符串格式

c++ - 如何使用具有类似 printf 格式的 C++ std::ostream?

javascript - 如何设置 VSCode 以将花括号放在新行上?

Java - 将双值格式化为美元金额

asp.net - 如何在 ASP.NET RadioButtonList 中的项目之间添加空格

c# - 如何格式化 Visual Studio 2012 中的所有文件?

java - 使用 Java 将电话号码转换为国际格式 (E.164) 的最佳方法是什么?

html - 在 Visual Studio Code 中格式化 html 代码,使属性位于不同的行

xml - 如何在 sublime 3 中安装 sublime text indent xml