Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) + "."); } 
like image 540
ajanic0le Avatar asked Dec 09 '12 20:12

ajanic0le


People also ask

Can I format a double in Java?

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.

What format is used for dollar amounts?

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.


1 Answers

Use NumberFormat.getCurrencyInstance():

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

Output:

$123.46 
like image 151
arshajii Avatar answered Sep 22 '22 00:09

arshajii