检查浮点数是否具有指定数量的数字和小数位

时间:2019-04-20 23:59:58

标签: python

我想检查浮点数是否具有指定数量的数字和小数位。

具体地说,我想检查输入是否有五位数字,紧跟一位小数位

例如54321.4

我尝试研究Regexp,但是我想先看看是否有一个更简单的解决方案。

# I've started with the below code

def getNum():
    num = float(input('Enter number with 5 digits and 1 decimal place:'))

    while not len(str(abs(num))) == 5:
      print('Error: Number must have exactly five digits followed by one 
      decimal place.\n')
      num = float(input('Enter number with 5 digits and 1 decimal place:'))

    return num

print(getNum())

例如,如果将输入123传递到getNum函数中,它将继续提示用户再次输入,直到用户输入的数字由五位数字和第五位精确到小数点后一位。

1 个答案:

答案 0 :(得分:0)

在这种情况下,正则表达式是最简单的解决方案–无需回避它。

import re

# Explanation:
#   ^      start of string
#   \d{5}  5 digits
#   \.     literal period
#   \d     digit
#   $      end of string
rgx = re.compile(r'^\d{5}\.\d$')

tests = [
    '12345.6',
    'hi',
    '12345.67',
]

for s in tests:
    m = rgx.search(s)
    print(bool(m), s)

输出:

True 12345.6
False hi
False 12345.67