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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了检查浮点数是否具有指定的位数和小数位数相关的知识,希望对你有一定的参考价值。

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

具体来说,我想检查输入是否有五位数后跟一个小数位

方程54321

我试过看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.
')
      num = float(input('Enter number with 5 digits and 1 decimal place:'))

    return num

print(getNum())

例如,如果123的输入被传递到getNum函数,它应该继续提示用户再次输入,直到用户输入一个五位数字和第五位数后面的一个小数位数。

答案

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

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

以上是关于检查浮点数是否具有指定的位数和小数位数的主要内容,如果未能解决你的问题,请参考以下文章