Python 如何计算用户输入的包含0的浮点小数位数?
我需要计算用户输入的浮点中的小数位数,这样我的代码就不会接受任何小数位数大于或小于2的数字(这个数字应该是一个价格)。这是我的密码:Python 如何计算用户输入的包含0的浮点小数位数?,python,floating-point,Python,Floating Point,我需要计算用户输入的浮点中的小数位数,这样我的代码就不会接受任何小数位数大于或小于2的数字(这个数字应该是一个价格)。这是我的密码: while(flag == True): try: price = input("Enter the price: ") price = float(price) flag = False #price must be positiv
while(flag == True):
try:
price = input("Enter the price: ")
price = float(price)
flag = False
#price must be positive
if float(price) < 0:
print("Invalid input for the new price.")
flag = True
#check for 2 decimal places
decimal = str(price)
decimal = decimal.split(".")
if len(decimal[1]) != 2:
print("Invalid input for the new price.")
flag = True
while(标志==True):
尝试:
价格=输入(“输入价格:”)
价格=浮动(价格)
flag=False
#价格必须是正数
如果浮动(价格)<0:
打印(“新价格的输入无效”)
flag=True
#检查小数点后2位
十进制=str(价格)
十进制=十进制分割(“.”)
如果len(十进制[1])!=2:
打印(“新价格的输入无效”)
flag=True
到目前为止,它是有效的,除非我输入一个类似6.50的价格,其中最后一位小数点是0。出于某种原因,它不接受以0结尾的任何数字作为小数点后2位。如何解决此问题?只要颠倒检查和浮点转换顺序,就不会出现浮点转换隐式剥离
'0'
的问题:
str(float('6.50'))
# '6.5'
做某事,例如:
# price = input("Enter the price: ")
price = raw_input("Enter the price: ") # python2
try:
assert len(price.split(".")[1]) == 2
price = float(price)
except (AssertionError, ValueError):
print("Invalid input for the new price.")
价格的
类型是什么?你为什么不直接检查用户输入,而这应该是一个字符串呢?@schwobasegll请参阅更新的代码你根本不应该将价格转换为float
!浮点用于连续刻度的测量,但货币总是以离散单位进行测量,因此您应该避免使用浮点
,直接使用。当我输入6.50时,我仍然得到无效的价格输入,不确定原因