Java - format double value as dollar amount

2019-01-09 05:18发布

问题:

I need to format the double "amt" as a dollar amount println("$" + dollars + "." + cents) such that there are two digits after the decimal.

What is the best way to go about doing so?

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) + ".");
}

回答1:

Use NumberFormat.getCurrencyInstance():

double amt = 123.456;    

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

Output:

$123.46


回答2:

You can use a DecimalFormat

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

That will give you a print out with always 2dp.

But really, you should be using BigDecimal for money, because of floating point issues



回答3:

Use DecimalFormat to print a decimal value in desired format e.g.

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

If you wish to display $ amount in US number format than try:

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

Using .00, it always prints two decimal points irrespective of their presence. If you want to print decimal only when they are present then use .## in the format string.



回答4:

You can use printf for a one liner

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

This will always print two decimal places, rounding as required.



回答5:

Use BigDecimal instead of double for currency types. In Java Puzzlers book we see:

System.out.println(2.00 - 1.10);

and you can see it will not be 0.9.

String.format() has patterns for formatting numbers.