【问题标题】:How to use Java's DecimalFormat for "smart" currency formatting?如何使用 Java 的 DecimalFormat 进行“智能”货币格式化?
【发布时间】:2011-06-29 08:06:08
【问题描述】:

我想使用 Java 的 DecimalFormat 来像这样格式化双精度:

#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”。

【问题讨论】:

  • 顺便说一句,使用双精度表示货币价值是个坏主意:stackoverflow.com/q/3730019/56285
  • 顺便说一句,银行中的大多数价格都表示为double(或int,精度固定)。

标签: java formatting decimalformat


【解决方案1】:

一定要用DecimalFormat吗?

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

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

【讨论】:

  • 'currencyString.replaceAll( regexp, String)' 在这种情况下效率低下。 'currencyString = currencyString.replace(".00", "");'效率更高。 replaceAll 需要编译 Pattern、创建 Matcher 等。这可能会非常昂贵,尤其是在资源有限的移动设备 (Android) 上的显示循环中执行代码时。
  • 值得注意的是,NumberFormat.getCurrencyInstance() 将仅在您的 Locale 设置为 US 时使用 $ 格式。要明确指定货币,您可以传递Locale - 例如NumberFormat.getCurrencyInstance(Locale.US) 这里
【解决方案2】:

使用数字格式:

NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
double doublePayment = 100.13;
String s = n.format(doublePayment);
System.out.println(s);

另外,不要使用双精度数来表示精确值。如果您在 Monte Carlo 方法中使用货币值(无论如何值都不准确),则首选 double。

另请参阅:Write Java programs to calculate and format currency

【讨论】:

  • 这不适用于案例 #1 ...它将 100 格式化为“$100.00”而不是“$100”
  • 是的,这不包括 setMinimumFractionDigits(0) 的情况。
【解决方案3】:

试试

new DecimalFormat("'$'0.00");

编辑:

我试过了

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));

得到了

$100.00
$100.50
$100.41

【讨论】:

  • 这不适用于案例 #1 ...它将 100 格式化为“$100.00”而不是“$100”
  • DecimalFormat("0.00") 用于解析成双精度。谢谢你这个简单的回答
【解决方案4】:

尝试使用

DecimalFormat.setMinimumFractionDigits(2);
DecimalFormat.setMaximumFractionDigits(2);

【讨论】:

  • 确实如此! codepublic class Testing { /** * @param args */ public static void main(String[] args) { double d = 100.5; DecimalFormat df = new DecimalFormat("'$'0.##"); df.setMaximumFractionDigits(2); df.setMinimumFractionDigits(2);字符串货币 = df.format(d); System.out.println(货币); } } code
  • @Peter,你是说案例#1吗?这就是这似乎不起作用的地方(Mac 上的 Java 1.6.0_22),产生“$100.00”而不是 OP 想要的“$100”。
  • @Jonik 是的,很抱歉打错了字。我基本上已经确定使用 DecimalFormat 是不可能的,并且已经转向其他方法来解决这个问题。谢谢!
  • 好吧,你是对的,如果你测试codeif(currency.substring(currency.indexOf(".")).equals("00" )) { 货币 = currency.substring(0,currency.indexOf(".")) } code
【解决方案5】:

您可以勾选“是否为整数”并选择所需的数字格式。

public class test {

  public static void main(String[] args){
    System.out.println(function(100d));
    System.out.println(function(100.5d));
    System.out.println(function(100.42d));
  }

  public static String function(Double doubleValue){
    boolean isWholeNumber=(doubleValue == Math.round(doubleValue));
    DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.GERMAN);
    formatSymbols.setDecimalSeparator('.');

    String pattern= isWholeNumber ? "#.##" : "#.00";    
    DecimalFormat df = new DecimalFormat(pattern, formatSymbols);
    return df.format(doubleValue);
  }
}

会给出你想要的:

100
100.50
100.42

【讨论】:

    【解决方案6】:

    您可以使用以下格式:

    DecimalFormat dformat = new DecimalFormat("$#.##");

    【讨论】:

      【解决方案7】:

      我知道为时已晚。但是以下对我有用:

      DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.UK);
      new DecimalFormat("\u00A4#######0.00",otherSymbols).format(totalSale);
      
       \u00A4 : acts as a placeholder for currency symbol
       #######0.00 : acts as a placeholder pattern for actual number with 2 decimal 
       places precision.   
      

      希望这对以后阅读本文的人有所帮助:)

      【讨论】:

        【解决方案8】:

        您可以尝试使用两个不同的DecimalFormat 对象,具体情况如下:

        double d=100;
        double d2=100.5;
        double d3=100.41;
        
        DecimalFormat df=new DecimalFormat("'$'0.00");
        
        if(d%1==0){ // this is to check a whole number
            DecimalFormat df2=new DecimalFormat("'$'");
            System.out.println(df2.format(d));
        }
        
        System.out.println(df.format(d2));
        System.out.println(df.format(d3));
        
        Output:-
        $100
        $100.50
        $100.41
        

        【讨论】:

          【解决方案9】:

          您可以使用 Java Money API 来实现这一点。 (虽然这不是使用DecialFormat)

          long amountInCents = ...;
          double amountInEuro = amountInCents / 100.00;
          
          String customPattern; 
          if (minimumOrderValueInCents % 100 == 0) {
              customPattern = "# ¤";
          } else {
              customPattern = "#.## ¤";
          }
          
          Money minDeliveryAmount = Money.of(amountInEuro, "EUR");
          MonetaryAmountFormat formatter = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder.of(Locale.GERMANY)
                      .set(CurrencyStyle.SYMBOL)
                      .set("pattern", customPattern)
                      .build());
          
          System.out.println(minDeliveryAmount);
          

          【讨论】:

            【解决方案10】:

            printf 也可以。

            例子:

            双任何数字 = 100; printf("值为 %4.2f ", anyNumber);

            输出:

            值为 100.00

            4.2 表示强制数字在小数点后有两位数。 4 控制小数点右边的位数。

            【讨论】:

            • 这不能处理为较大的数字添加逗号,但在给出示例的情况下它可以工作。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-18
            相关资源
            最近更新 更多