Forked from codingforentrepreneurs/number_str_to_float.py
Created
September 14, 2021 07:46
-
-
Save LowerDeez/a15c17678e1167e63165680d2697e8fc to your computer and use it in GitHub Desktop.
A simple python function to convert a number string into a float if possible.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fractions import Fraction | |
def number_str_to_float(amount_str:str) -> (any, bool): | |
""" | |
Take in an amount string to return float (if possible). | |
Valid string returns: | |
Float | |
Boolean -> True | |
Invalid string Returns | |
Original String | |
Boolean -> False | |
Examples: | |
1 1/2 -> 1.5, True | |
32 -> 32.0, True | |
Abc -> Abc, False | |
""" | |
success = False | |
number_as_float = amount_str | |
try: | |
number_as_float = float(sum(Fraction(s) for s in f"{amount_str}".split())) | |
except: | |
pass | |
if isinstance(number_as_float, float): | |
success = True | |
return number_as_float, success |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment