【问题标题】:Java - format double value as dollar amountJava - 将双值格式化为美元金额
【发布时间】:2012-12-09 20:20:22
【问题描述】:

我需要将双“amt”格式化为美元金额 println("$" + dollar + "." + cents),以便小数点后有两位数。

这样做的最佳方法是什么?

if (payOrCharge <= 1)
{
    System.out.println("Please enter the payment amount:");
    double amt = keyboard.nextDouble();
    cOne.makePayment(amt);
    System.out.println("-------------------------------");
    System.out.println("The original balance is " + cardBalance + ".");
    System.out.println("You made a payment in the amount of " + amt + ".");
    System.out.println("The new balance is " + (cardBalance - amt) + ".");
}
else if (payOrCharge >= 2)
{
    System.out.println("Please enter the charged amount:");
    double amt = keyboard.nextDouble();
    cOne.addCharge(amt);
    System.out.println("-------------------------------");
    System.out.println("The original balance is $" + cardBalance + ".");
    System.out.println("You added a charge in the amount of " + amt + ".");
    System.out.println("The new balance is " + (cardBalance + amt) + ".");
}

【问题讨论】:

标签: java formatting double


【解决方案1】:

使用NumberFormat.getCurrencyInstance():

double amt = 123.456;    

NumberFormat formatter = NumberFormat.getCurrencyInstance();
System.out.println(formatter.format(amt));

输出:

$123.46

【讨论】:

  • 这是正确的答案,您需要使用“import java.text.NumberFormat;”导入 util在顶部。
  • 我不得不稍微操作一下以确保我得到 $ 符号。 NumberFormat.getCurrencyInstance(locale.US)
  • 这个答案有效,直到您考虑到您没有明确设置本地。这是我刚刚在我的 android 应用程序中遇到的问题,其中用户将英国设置为美国应用程序的本地(遗物代码,我没有写)。很高兴注意到这个陷阱,否则你会得到不正确的货币值。
  • 如果你想设置语言环境,你也需要import java.util.Locale;。另请注意,Locale 总是拼写为大写“L”。
  • 如何让它替换2个小数位?还是 5 个?
【解决方案2】:

您可以使用 DecimalFormat

DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(amt));

这将为您提供始终 2dp 的打印输出。

但实际上,由于浮点问题,您应该使用 BigDecimal 来赚钱

【讨论】:

    【解决方案3】:

    使用DecimalFormat 以所需格式打印十进制值,例如

    DecimalFormat dFormat = new DecimalFormat("#.00");
    System.out.println("$" + dFormat.format(amt));
    

    如果您希望以美国数字格式显示 $ 金额,请尝试:

    DecimalFormat dFormat = new DecimalFormat("####,###,###.00");
    System.out.println("$" + dFormat.format(amt));
    

    使用.00,它总是打印两个小数点,无论它们是否存在。如果您只想在十进制出现时打印它们,请在格式字符串中使用.##。

    【讨论】:

    • ...然后在格式字符串中使用 .##。 - 这将显示 $5.5 而不是 $5.50
    【解决方案4】:

    您可以将 printf 用于单行

    System.out.printf("The original balance is $%.2f.%n", cardBalance);
    

    这将始终打印两位小数,并根据需要四舍五入。

    【讨论】:

      【解决方案5】:

      对货币类型使用 BigDecimal 而不是 double。 在 Java Puzzlers 书中我们看到:

      System.out.println(2.00 - 1.10);
      

      你可以看到它不会是 0.9。

      String.format() 具有格式化数字的模式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-26
        • 1970-01-01
        • 2020-01-25
        • 2023-03-21
        相关资源
        最近更新 更多