Python销售税计划,带有2个小数位,Money

时间:2014-01-22 21:59:54

标签: python decimal currency

我只是在学习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

我比编程和Python更熟悉SQL,所以我还在学习。

感谢您的时间。

# 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="") 

1 个答案:

答案 0 :(得分: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位小数。

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