gpt4 book ai didi

Java - 将双值格式化为美元金额

转载 作者:bug小助手 更新时间:2023-10-28 10:44:15 26 4
gpt4 key购买 nike

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

最佳答案

使用 NumberFormat.getCurrencyInstance() :

double amt = 123.456;    

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

输出:

$123.46

关于Java - 将双值格式化为美元金额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13791409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com