如何检查输入是否为十进制数?

3
我希望有一个输入框,可以持续要求输入数据,除非输入的是小数点后只有两位或更少的数字。
number = input('please enter a number')  
while number **is not a decimal (insert code)**:  
. . . .number = input('incorrect input,\nplease enter a number')

你可以使用这个正则表达式\d*\.\d{1,2}来检查,但是似乎在这个问题上使用正则表达式不太干净 :) - Nil
“两位小数”是指小数点后只有两位数字吗?例如,1234151651.12 是可以的吗? - roippi
3个回答

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

@JonClements 哇,太棒了! - BartoszKP

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是否为有效的浮点数。


0

你可以写

if (yourinput%.01 != 0):

换句话说,如果第二位小数后面还有任何内容...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接