【发布时间】:2014-02-13 05:12:42
【问题描述】:
我刚刚学习 python,并且我的销售税程序运行良好,但试图让我的输入变量和浮点小数点正确。什么是获得小数位的正确方法,以显示只有 2 个小数位的货币价值。
我浏览了这些链接并找到了这些有用的链接,但仍然试图在这里更好地掌握小数和美分单位。
似乎我可能已经通过此链接找到了答案,但会将问题留给其他人学习。
How can I format 2 decimals in Python
Decimals to 2 places for money Python
Two Decimal Places For Money Field
如果我输入 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="")
【问题讨论】:
-
您至少两次链接到该答案。浮点运算不精确;要么使用字符串格式,要么使用
Decimals。