ajanic0le
ajanic0le

Reputation: 383

Java - format double value as dollar amount

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

Upvotes: 34

Views: 106956

Answers (5)

arshajii
arshajii

Reputation: 129477

Use NumberFormat.getCurrencyInstance():

double amt = 123.456;    

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

Output:

$123.46

Upvotes: 66

Yogendra Singh
Yogendra Singh

Reputation: 34367

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.

Upvotes: 8

user798182
user798182

Reputation:

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

Upvotes: 9

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7282

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533442

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.

Upvotes: 5

Related Questions