如何将Java的DecimalFormat用于“智能”货币格式? [英] How to use Java's DecimalFormat for "smart" currency formatting?

查看:163
本文介绍了如何将Java的DecimalFormat用于“智能”货币格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #1  -  100  - >我想用Java的DecimalFormat来格式化双精度。 $ 100 
#2 - 100.5 - > $ 100.50
#3 - 100.41 - > $ 100.41

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

 新的DecimalFormat('''0。##); 

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



编辑:

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

解决方案

是否必须使用 DecimalFormat



如果不是这样,看起来像下面这样:

 字符串currencyString = NumberFormat.getCurrencyInstance()。format(currencyNumber); 
//处理无格式格式化整数美元金额的奇怪异常
currencyString = currencyString.replaceAll(\\.00,);


I'd like to use Java's DecimalFormat to format doubles like so:

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

The best I can come up with so far is:

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

But this doesn't work for case #2, and instead outputs "$100.5"

Edit:

A lot of these answers are only considering cases #2 and #3 and not realizing that their solution will cause #1 to format 100 as "$100.00" instead of just "$100".

解决方案

Does it have to use DecimalFormat?

If not, it looks like the following should work:

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

这篇关于如何将Java的DecimalFormat用于“智能”货币格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆