33

我需要将双“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) + ".");
}
4

5 回答 5

62

使用NumberFormat.getCurrencyInstance()

double amt = 123.456;    

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

输出:

$123.46
于 2012-12-09T20:23:04.437 回答
9

您可以使用 DecimalFormat

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

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

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

于 2012-12-09T20:22:57.027 回答
8

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

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

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

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

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

于 2012-12-09T20:23:35.320 回答
5

您可以将 printf 用于一个衬里

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

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

于 2012-12-09T20:25:53.750 回答
1

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

System.out.println(2.00 - 1.10);

你可以看到它不会是 0.9。

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

于 2012-12-09T20:28:10.570 回答