如何使用Java的DecimalFormat进行"智能"货币格式化?

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)

  • 'currencyString.replaceAll(regexp,String)'在这种情况下效率低下.'currencyString = currencyString.replace(".00","");' 效率更高.replaceAll需要编译模式,创建匹配器等.这可能非常昂贵,特别是如果代码在具有有限资源(Android)的移动设备上的显示循环中执行. (2认同)

小智 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程序以计算和格式化货币


Bal*_*a R 5

尝试

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)

  • 这不适用于案例#1 ...它将100格式化为"$ 100.00"而不是"$ 100" (4认同)