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) + "."); }
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.
United States (U.S.) currency is formatted with a decimal point (.) as a separator between the dollars and cents. Some countries use a comma (,) instead of a decimal to indicate that separation.
Use NumberFormat.getCurrencyInstance():
double amt = 123.456; NumberFormat formatter = NumberFormat.getCurrencyInstance(); System.out.println(formatter.format(amt));
Output:
$123.46
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With