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

我需要将双“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

https://stackoverflow.com/questions/13791409/

相关文章:

html - 在 Visual Studio Code 中格式化 html 代码,使属性位于不同的行

c# - 如何格式化 Visual Studio 2012 中的所有文件?

c++ - 如何使用具有类似 printf 格式的 C++ std::ostream?

coding-style - 线宽格式标准

emacs - 在 Emacs 中,如何在一系列初始化语句中排列等号?

c - intptr_t 和 uintptr_t 的字符串格式

java - 日期和时间格式取决于区域设置

android - 点后 2 位 float

javascript - 如何设置 VSCode 以将花括号放在新行上?

java - 使用 Java 将电话号码转换为国际格式 (E.164) 的最佳方法是什么?