Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

How to convert number string or fraction to float

from fractions import Fraction


def number_str_to_float(amount_str):
    number_as_float = amount_str
    try:
        number_as_float = round(float(sum(Fraction(s)
                                for s in f"{amount_str}".split())), 2)
    except:
        print(f''{number_as_float}' is not a number or fraction')
    if isinstance(number_as_float, float):
        print(number_as_float)


number_str_to_float("5 1/3")

# Output
# 5.33
 
PREVIOUS NEXT
Tagged: #How #convert #number #string #fraction #float
ADD COMMENT
Topic
Name
8+3 =