2014-01-22 30 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位。

注意:我不确定您为什么要将税率显示为美元金额,因此我将其更改为百分比。