Iceman
Iceman

Reputation: 45

How do i check for incorrect decimal format?

I am putting together an error log that will be integrated into a GUI (General User Interface). The GUI allows requires the user to enter a decimal number that is less than 5 but more than 0, has no more than 2 decimal places and has only 1 decimal point. Checking value is less than 5 more than 0 is no problem, but how do i check that the other 2 points (must have 1 decimal point no more no less and must have 2 decimal places no more no less)

Additionally i will likely result in having 10-20 if statements any recommendations on a better format than using many if statements would be appreciated.

example code that i'm working with is below:

test1 = 0.65  # Test 1
test2 = 0.71  # Test 2
test3 = 0.12  # Test 3

tests =[test1,test2,test3]  #Create Test Array

tests.sort() # Sort Test array from largest to smalest so i can check that the test values are within max range of 0.1
print(tests)  #Print Array
lowtest = tests[0]  #set Low value
hightest = tests[2] # Set High Value
testvariance = hightest-lowtest # Check Variance
testvariance = round(testvariance,2)  # variance to 2 decimal places
print(testvariance) # variance

if test1 == 0:  #Check Value is entered as default value is 0
    print("Test 1 Missing")
elif test2 == 0: #Check Value is entered as default value is 0
    print("Test 2 Missing")
elif test3 == 0: #Check Value is entered as default value is 0
    print("Test 3 Missing")    
elif testvariance >=.1: # Check values are within range tolerance of 0.1
    print("Outside of test range tollerance")
elif testvariance <=.1  and testvariance>=0:
    print("Within Test Range") 
else:
    print("Error Unknown State")

Upvotes: 1

Views: 155

Answers (1)

ddejohn
ddejohn

Reputation: 8962

You can use a regular expression to tackle all these challenges simultaneously (assuming you are enforcing that two values come after the decimal, and that the user input is initially a string):

import re

pattern = re.compile(r"^[0-4]\.\d{2}$")

Demonstration:

In [2]: while True:
   ...:     print(pattern.findall(input()))
   ...:     print()
   ...:
1.12
['1.12']

0.52
['0.52']

0.0.0.0.
[]

5.00
[]

4.99
['4.99']

3.14
['3.14']

hello
[]

938176
[]

AU)(*E
[]

...3.14
[]

Note that you'll need to convert the values to float yourself.

If you want to allow for up to two decimal places to be included:

pattern = re.compile(r"^[0-4]\.\d{1,2}$")

Upvotes: 1

Related Questions