检查输入是否为浮点数并且小数点后正好有2个数字[重复]

时间:2021-09-02 17:17:13

This question already has an answer here:

这个问题在这里已有答案:

I'm working on a class project that requires me to obtain a float value from the user. This float value must have exactly two numbers after the decimal in order to be a valid input. This is what I have so far.

我正在研究一个需要我从用户那里获取浮点值的类项目。此浮点值必须在小数点后正好有两个数字才能成为有效输入。这就是我到目前为止所拥有的。

while True:
    try:
        cost = float(input("Enter the price: "))
        if cost % 1 == 0:
            print("Invalid input for price.")

        else:
            if cost > 0:
               return cost

    except ValueError:
        print("Invalid input for price.")

Comparing cost % 1 to 0 rules out ints and floats ending in .00, but I'm not sure how I could restrict the accepted input to a float with exactly 2 numbers after the decimal (i.e. x.xx). Also I believe I would need to accept a float like 5.00 so my method isn't going to cut it. I've tried converting cost to a str and setting restrictions on the length, but that still leaves it open to mistakes. Any advice?

比较成本%1到0排除以.00结尾的整数和浮点数,但是我不确定如何将接受的输入限制为小数点后正好有2个数字的浮点数(即x.xx)。另外我相信我需要接受像5.00这样的浮动,所以我的方法不会削减它。我已经尝试将成本转换为str并设置长度限制,但这仍然让它容易出错。任何建议?

4 个解决方案

#1


6  

You can check it before converting to float:

您可以在转换为float之前检查它:

cost = input("Enter the price: ")
if len(cost.rsplit('.')[-1]) == 2:
   print('2 digits after decimal point')

#2


1  

Use this code:

使用此代码:

>>> while True:
...     try:
...             x = float(raw_input('Enter the price: '))
...             y = str(x).split('.')
...             if len(y[-1]) != 2:
...                     raise ValueError
...     except ValueError:
...             print 'Please try again!'
...             pass
... 
Enter the price: hello
Please try again!
Enter the price: 5.6
Please try again!
Enter the price: 5.67
Enter the price: 7.65
Enter the price: 7
Please try again!
Enter the price: 

It gets the input as a float, and if the user does not enter a numerical value, it raises a ValueError by default. If it doesn't, then we get the string value of the price using str(x) and assign it to y, which we split by the decimal place. Then we can check if the last value in the list (the yx in $x.yz) has a length that is not equal to 2. If so, raise a ValueError.

它将输入作为浮点数,如果用户没有输入数值,则默认情况下会引发ValueError。如果没有,那么我们使用str(x)得到价格的字符串值并将其分配给y,我们用小数位分割。然后我们可以检查列表中的最后一个值($ x.yz中的yx)是否具有不等于2的长度。如果是,则引发ValueError。

#3


0  

Why make it so complicated?

为什么要这么复杂?

cost = raw_input('Enter the price: ')
if len(cost[cost.rfind('.')+1:]) != 2:
    raise ValueError('Must have two numbers after decimal point')
try:
    cost = float(cost)
except ValueError:
    print('Please enter a valid number')

#4


0  

Use raw_input() instead of input(). That is safer (no use of eval) and it returns the actual string the user entered.

使用raw_input()而不是input()。这更安全(不使用eval)并返回用户输入的实际字符串。

Then check the string with a regular expression.

然后使用正则表达式检查字符串。

>>> import re
>>> s = raw_input('Enter a price: ')
Enter a price: 3.14
>>> if not re.match(r'[0-9]*\.[0-9]{2}', s):
        print 'Not a valid price'

>>> price = float(s)

#1


6  

You can check it before converting to float:

您可以在转换为float之前检查它:

cost = input("Enter the price: ")
if len(cost.rsplit('.')[-1]) == 2:
   print('2 digits after decimal point')

#2


1  

Use this code:

使用此代码:

>>> while True:
...     try:
...             x = float(raw_input('Enter the price: '))
...             y = str(x).split('.')
...             if len(y[-1]) != 2:
...                     raise ValueError
...     except ValueError:
...             print 'Please try again!'
...             pass
... 
Enter the price: hello
Please try again!
Enter the price: 5.6
Please try again!
Enter the price: 5.67
Enter the price: 7.65
Enter the price: 7
Please try again!
Enter the price: 

It gets the input as a float, and if the user does not enter a numerical value, it raises a ValueError by default. If it doesn't, then we get the string value of the price using str(x) and assign it to y, which we split by the decimal place. Then we can check if the last value in the list (the yx in $x.yz) has a length that is not equal to 2. If so, raise a ValueError.

它将输入作为浮点数,如果用户没有输入数值,则默认情况下会引发ValueError。如果没有,那么我们使用str(x)得到价格的字符串值并将其分配给y,我们用小数位分割。然后我们可以检查列表中的最后一个值($ x.yz中的yx)是否具有不等于2的长度。如果是,则引发ValueError。

#3


0  

Why make it so complicated?

为什么要这么复杂?

cost = raw_input('Enter the price: ')
if len(cost[cost.rfind('.')+1:]) != 2:
    raise ValueError('Must have two numbers after decimal point')
try:
    cost = float(cost)
except ValueError:
    print('Please enter a valid number')

#4


0  

Use raw_input() instead of input(). That is safer (no use of eval) and it returns the actual string the user entered.

使用raw_input()而不是input()。这更安全(不使用eval)并返回用户输入的实际字符串。

Then check the string with a regular expression.

然后使用正则表达式检查字符串。

>>> import re
>>> s = raw_input('Enter a price: ')
Enter a price: 3.14
>>> if not re.match(r'[0-9]*\.[0-9]{2}', s):
        print 'Not a valid price'

>>> price = float(s)