2016-02-11 15 views
1

我是高中的初中。經歷一段艱難的時間才搞清楚如何使用金錢格式。我正在練習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); 
} 
} 

我只是想用錢的格式,但我不知道怎麼樣。我確定這是一個愚蠢的問題,但謝謝你的幫助!

+0

剛擡起頭,你應該**從不**使用浮點數來存儲貨幣。格式以二進制形式存儲數據,以便將其表示爲某個無符號二進制整數(有效數)* 2的一些冪。因爲它存儲在兩個而不是十個的權力,你可能會遇到很多麻煩。相反,使用定點方法(例如,將美分數存儲在「長」中)[更多閱讀](https://en.wikipedia.org/wiki/Floating_point) –

回答

1

更改您的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 
+0

完美運作。希望我的老師會接受它,我想她正在談論一種不同的方式來做到這一點。 –

+0

看我的編輯;在java.text中有一個NumberFormat也是有幫助的。讓我知道你是否需要幫助。 –