How to check if a float is in a specific range and has a given number of decimal digits?

How to check if a floating point value is within the range (0.50.150.00) and has two decimal digits?

For example, 15.22366 must be false (too many decimal digits). But 15.22 should be true.

I tried something like:

data= input()
if data in range(0.50,150.00):
   return True
+8
source share
5 answers

Is this what you are looking for?

def check(value):
    if 0.50 <= value <= 150 and round(value,2)==value:
        return True
    return False

Based on your comment:

i input 15.22366 it will return true; therefore, I indicated a range; he must accept 15.22

, . . , , 1.40. " ":

>>> f = 1.40
>>> print f
1.4

. Python , . , f, :

>>> from decimal import Decimal
>>> Decimal(f)
Decimal('1.399999999999999911182158029987476766109466552734375')

2 , f ?

, , round(...,2), . - " " . . :

>>> for v in [ 1.40,
...            1.405,
...            1.399999999999999911182158029987476766109466552734375,
...            1.39999999999999991118,
...            1.3999999999999991118]:
...     print check(v), v
...
True 1.4
False 1.405
True 1.4
True 1.4
False 1.4

, . , .


, , , , " ". Python decimal .

+17

float - , Decimal.

python . ( )

2 () .

, 2 , (, 0,1) 2.

,

, Python, 53 Python, , , , , , .

round() , , .

, ,

, , , decimal.

, 2 , .


: ,

, 2 , [50, 15000] 100, float .

import random
random.randint(50, 15000)/100.0
+3

round?

round(random.uniform(0.5, 150.0), 2)
+2

, . Cyber , , . :

n = random.uniform(0.5, 150)
print '%.2f' % n               # 58.03
+1

- '.' , . > 2, . , , .

a=15.22366
if len(str(a).split('.')[1])>2:
    if 0.50 <= value <= 150:
        <do your stuff>>
0

All Articles