Python: is_mathematical_decimal(num_str)

Python has the methods isnumeric, isdigit, and isdecimal, and absolutely none of them will return true for a traditional decimal number AKA float, such as 1.23. Supposedly, the only solution for this is to effectively do a try-catch with a ValueError. 

But that's disgusting and I hate it. 

Why wouldn't they have a third function for this? 

Anyway, this is my (not super well tested) implementation for it. It worked well enough for the MIT OCW exercise I was doing, anyway. 

def is_mathematical_decimal(num_str):
if len(num_str) == 0:
return False
if num_str[0] == "-":
num_str = num_str[1:]
for char in num_str:
if not char.isnumeric() and not char == ".":
return False
return True

So if we have any character that's not a number OR a period, OR a minus sign at the BEGINNING, then it's not a mathematical decimal. 

There should be some safeguarding against invalid inputs here, maybe, but honestly I think this works. I'll have to test it more later. 

Quick tests and outputs: 
# is_mathematical_decimal test cases:
# Expected: True
print(str(is_mathematical_decimal("1.23")))
# Expected: True
print(str(is_mathematical_decimal("123")))
# Expected: True
print(str(is_mathematical_decimal("-1.23")))
# Expected: False
print(str(is_mathematical_decimal("1.-23")))
# Expected: False
print(str(is_mathematical_decimal("1.23aaaa")))
# Expected: False
print(str(is_mathematical_decimal("z")))

Results:

True
True
True
False
False
False

As expected!

Comments

Popular posts from this blog

Unleashing my inner Disney Princess ✩₊˚.⋆☾⋆⁺₊✧ at the 2024 Disney Princesses Half Marathon

The 20-something types of Computer Science majors

The Evenstar