【发布时间】:2016-02-11 00:51:13
【问题描述】:
我是一名初中生。很难弄清楚如何使用货币格式。我正在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);
}
}
我只想使用货币格式,但我不确定如何使用。我敢肯定这是一个愚蠢的问题,但感谢您的帮助!
【问题讨论】:
-
请注意,您应该永远使用浮点数来存储货币。该格式以二进制形式存储数据,因此它表示为一些无符号二进制整数(有效数)* 2 的某个幂。因为它是以 2 而不是 10 的幂存储的,所以你可能会遇到很多麻烦。而是使用定点方法(例如,将美分数存储在
long中)more reading