Java 货币格式-我如何使用它?

Java 货币格式-我如何使用它?,java,currency,Java,Currency,我是一名初中生。很难弄清楚如何使用货币形式。我在《Java编程指南》(第二版)中做一个练习,我必须提示员工汉堡、薯条和苏打水的数量 薯条1.09美元,汉堡1.69美元,苏打水0.99美元 这是我的密码: import java.util.Scanner; /** * Order pg. 101 * * Garret Mantz * 2/10/2016 */ public class Order { public static void main(String[]args) { f

我是一名初中生。很难弄清楚如何使用货币形式。我在《Java编程指南》(第二版)中做一个练习,我必须提示员工汉堡、薯条和苏打水的数量

薯条1.09美元,汉堡1.69美元,苏打水0.99美元

这是我的密码:

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);
 }
}

我只是想使用货币形式,但我不确定如何使用。我肯定这是个愚蠢的问题,但谢谢你的帮助

将println更改为这些,看看这是否有帮助:

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);
还有一点:

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);
输出:

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

这非常有效。希望我的老师会接受,我想她说的是一种不同的方法;java.text中有一个NumberFormat,这也很有帮助。如果您需要帮助,请告诉我。提醒一下,您永远不应该使用浮点数来存储货币。该格式以二进制形式存储数据,以便将其表示为某个无符号二进制整数(有效位)*二的某个幂。因为它是二次幂而不是十次幂,你可能会遇到很多麻烦。而是使用定点方法(例如,将美分数存储在
长的