Pet*_*ter 29 java formatting decimalformat
我想使用Java的DecimalFormat来格式化双打,如下所示:
#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41
Run Code Online (Sandbox Code Playgroud)
到目前为止我能想出的最好的是:
new DecimalFormat("'$'0.##");
Run Code Online (Sandbox Code Playgroud)
但这不适用于案例#2,而是输出"$ 100.5"
编辑:
很多这些答案只考虑案例#2和#3而没有意识到他们的解决方案会导致#1将100格式化为"$ 100.00"而不仅仅是"$ 100".
Bra*_*ain 22
它必须使用DecimalFormat吗?
如果没有,看起来应该如下:
String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
//Handle the weird exception of formatting whole dollar amounts with no decimal
currencyString = currencyString.replaceAll("\\.00", "");
Run Code Online (Sandbox Code Playgroud)
小智 7
使用NumberFormat:
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double doublePayment = 100.13;
String s = n.format(doublePayment);
System.out.println(s);
Run Code Online (Sandbox Code Playgroud)
另外,请勿使用双精度来表示精确值.如果您在蒙特卡罗方法中使用货币值(其中值无论如何都不准确),则首选double.
另请参阅:编写Java程序以计算和格式化货币
尝试
new DecimalFormat("'$'0.00");
Run Code Online (Sandbox Code Playgroud)
编辑:
我试过了
DecimalFormat d = new DecimalFormat("'$'0.00");
System.out.println(d.format(100));
System.out.println(d.format(100.5));
System.out.println(d.format(100.41));
Run Code Online (Sandbox Code Playgroud)
得到了
$100.00
$100.50
$100.41
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67211 次 |
| 最近记录: |