2014-01-22 44 views
0

我剛剛學習python,並有我的銷售稅計劃運行沒關係,但試圖讓我的輸入變量和浮動小數點正確。以小數點後兩位顯示貨幣值的正確方法是什麼?Python銷售稅計劃與2個小數位的地方,錢

我已經查看了這些鏈接,發現了這些有用的鏈接,但仍試圖在這裏更好地掌握小數和美分單位。

似乎我可能已通過此鏈接找到了我的答案,但會將問題留給其他人學習。

How can I format 2 decimals in Python

Decimals to 2 places for money Python

Two Decimal Places For Money Field

Money and 2 Decimal places.

看來,如果我進入5作爲我的價格,我得到5.300000000000001

我比較熟悉SQL比編程和Python,所以我還在學習。

謝謝你的時間。

# 01/22/14 
# Python Program Sales Tax 
# 
#Design a program that will ask the user to enter the amount of a purchase. 
#The program should then compute the state and county sales tax. Assume the 
#state sales tax is 4 percent and the countysalestax is 2 percent. The program 
#should display the amount of the purchase, the state sales tax, the county 
#sales tax, the total sales tax, and the total of the sale (which is the sum of 
#the amount of purchase plus the total sales tax) 
#Use the value 0.02, and 0.04 

# Display "Enter item_price Amount " 
# Input item_price 
# Display "state_sales_tax is 4% " 
# Set state_sales_tax = 0.04 
# Display "county_sales_tax is 2% " 
# Set county_sales_tax = 0.02 
# print("Your total cost is $",total_price,".",sep="") 


county_tax_rate = 0.02 
state_tax_rate = 0.04 
tax_rate = county_tax_rate + state_tax_rate 

item_price = float(input("Please enter the price of your item.\n")) 
total_tax_rate = county_tax_rate + state_tax_rate 
total_price = item_price * (1 + tax_rate) 
print("Your Total Sales Cost is $",total_price,".",sep="") 
print("Your Purchase Amount was $",item_price,".",sep="") 
print("Your County Tax Rate was $", county_tax_rate,".",sep="") 
print("Your State Tax Rate was $", state_tax_rate,".",sep="") 
print("Your Total Tax Rate was $", total_tax_rate,".",sep="") 
print("Your Total Tax Rate was $", total_tax_rate,".",sep="") 
+0

您鏈接到答案至少兩次。浮點運算是不精確的;要麼使用字符串格式,要麼使用'Decimals'。 – roippi

回答

3

當使用美元金額時,我會建議將所有東西都轉換爲美分。因此,將所有東西(當然除了稅率)乘以100,然後對其進行任何算術運算,最後將其轉換回浮點數。另外,tax_rate和total_tax_rate是等價的,所以只需使用一個。我想上面的改變爲:

county_tax_rate = 0.02 
state_tax_rate = 0.04 
tax_rate = county_tax_rate + state_tax_rate 

item_price = float(input("Please enter the price of your item: ")) 
item_price = int(100 * item_price) # Item price in cents 
total_price = item_price * (1 + tax_rate) # Total price in cents 

print("Your Total Sales Cost is ${:0.2f}".format(total_price/100.0)) 
print("Your Purchase Amount was ${:0.2f}".format(item_price/100.0)) 
print("Your County Tax Rate was {}%".format(int(county_tax_rate * 100))) 
print("Your State Tax Rate was {}%".format(int(state_tax_rate * 100))) 
print("Your Total Tax Rate was {}%".format(int(tax_rate * 100))) 

{:0.2f}格式字符串需要一個浮動,並顯示出到小數點後2位。

注意:我不確定您爲什麼要將稅率顯示爲美元金額,因此我將其更改爲百分比。