Search code examples
pythonfloating-pointfractions

Python string either fraction or float to float


I have a problem where I want to take a string which could say either a fraction like '1/6' or a float '2.0', and have them both evaluate to a final float value. What I don't know how to do is deal with the potential for either case to come up or how process them so I get the float output of the fraction.

numberArray = []
d1 = 0
d2 = 0

fileInput = f.readlines()

for line in fileInput:
    numberArray.append(line)

for i in numberArray:
    content = i.replace("\n","").split(" ")

    d1 = (float(content[0]))
    //The rest of data in the line is stored below (d2, d3 etc), but this isn't 
    // important. The important part is the first item that comes up in each line, 
    //and whether or not it is a fraction or already a float.

Input:

1/3 ...(rest of the line, not important)
2.0 ...

Output:

d1 (line1, item1) = 0.33
d2 (line1, item2) = ...

d1 (line2, item1) = 2.0
d2 (line2, item2) = ...

Solution

  • I'm new to python so this may not be the most elegant solution, but maybe something like:

    import re
    
    values = ["3.444", "3", "1/3", "1/5"]
    
    def to_float(str):
        is_frac = bool(re.search("/", str))
        if is_frac:
            num_den = str.split("/")
            return float(num_den[0]) / float(num_den[1])
        else:
            return float(str)
    
    floats = [to_float(i) for i in values]
    print(floats)