如何检查输入是否为小数?

时间:2014-01-12 21:32:42

标签: python input

我希望输入继续要求输入,除非输入是一个小数为2或更少的数字。

number = input('please enter a number')  
while number **is not a decimal (insert code)**:  
. . . .number = input('incorrect input,\nplease enter a number')

3 个答案:

答案 0 :(得分:2)

您可以使用评论中提到的正则表达式:

import re

def hasAtMostTwoDecimalDigits(x):
    return re.match("^\d*.\d{0,2}$", x)

number = input("please enter a number")
while not hasAtMostTwoDecimalDigits(number):
    number = input("incorrect input,\nplease enter a number")

或使用decimal模块:

from decimal import Decimal

def hasAtMostTwoDecimalDigits(x):
    x = Decimal(x)
    return int(1000*x)==10*int(100*x)

number = input("please enter a number")
while not hasAtMostTwoDecimalDigits(number):
    number = input("incorrect input,\nplease enter a number")

如评论Jon Clements所述,这可以更简单:

def hasAtMostTwoDecimalDigits(x):
    return Decimal(x).as_tuple().exponent >= -2

答案 1 :(得分:1)

由于input为您提供了一个字符串,因此将其视为一个字符串似乎最为直接

while len(number.partition('.')[2]) <= 2:

虽然你真的应该把它封装到一个检查它是一个完全有效的数字的函数中。只需执行上述操作即可获得123..之类的内容。所以你可以这样做:

def is_valid(num):
    try:
        float(num)
        return len(a.partition('.')[2]) <= 2
    except Exception:
        return False

我们让float(num)处理num是否有效浮动。

答案 2 :(得分:0)

你可以写

if (yourinput%.01 != 0):

换句话说,如果在第二位小数之后有什么东西......