简体   繁体   中英

Money format - how do I use it?

I'm a junior in high school. Having a tough time figuring out how to use money format. I'm doing an exercise in A Guide to Programming in Java (Second Edition) where I have to prompt the employees for the number of burgers, fries, and sodas.

Fries are $1.09, burgers are $1.69, and sodas are $0.99.

Here is my code:

import java.util.Scanner;
/**
 * Order pg. 101
 * 
 * Garret Mantz
 * 2/10/2016
 */
public class Order {

public static void main(String[]args) {

final double pburgers=1.69;
final double pfries=1.09;
final double psodas=0.99;
final double ptax=0.065;
double burgers;
double fries;
double sodas;
double totaltax;
double total;
double tax;
double tendered;
double change;

Scanner input = new Scanner(System.in);


System.out.print("Enter the amount of burgers: ");
burgers = input.nextDouble();
System.out.print("Enter the amount of fries: ");
fries = input.nextDouble();
System.out.print("Enter the amount of sodas: ");
sodas = input.nextDouble();
System.out.print("Enter the amount tendered: ");
tendered = input.nextDouble();



totaltax = (burgers*pburgers)+(fries*pfries)+(sodas*psodas);
tax = totaltax*ptax;
total = totaltax + tax;
change = tendered - total;


System.out.println("Your total before tax is: \n" + totaltax);
System.out.println("Tax: \n" +  tax);
System.out.println("Your final total is: \n" + total);
System.out.println("Your change is: \n" + change);
 }
}

I just want to use the money format, but I'm not sure how. I'm sure it's a dumb question, but thank you for helping out!

Change your println to these, and see if that helps:

System.out.format("Your total before tax is: $%-5.2f\n", totaltax);
System.out.format("Tax: $%-5.2f\n", tax);
System.out.format("Your final total is: $%-5.2f\n", total);
System.out.format("Your change is: $%-5.2f\n", change);

There is also this:

NumberFormat formatter = NumberFormat.getCurrencyInstance();
String totalTaxString = formatter.format(totaltax);
String taxString = formatter.format(tax);
String totalString = formatter.format(total);
String changeString = formatter.format(change);

System.out.format("Your total before tax is: %s\n", totalTaxString);
System.out.format("Tax: %s\n", taxString);
System.out.format("Your final total is: %s\n", totalString);
System.out.format("Your change is: %s\n", changeString);

Output:

Your total before tax is: $8.53 
Tax: $0.55 
Your final total is: $9.08 
Your change is: $10.92

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM