Python- Convert a mixed number to a float

Posted by user345660 on Stack Overflow See other posts from Stack Overflow or by user345660
Published on 2010-05-21T00:02:28Z Indexed on 2010/05/21 0:10 UTC
Read the original article Hit count: 600

Filed under:
|
|

I want to make a function that converts mixed numbers and fractions (as strings) to floats. Here's some examples:

'1 1/2' -> 1.5
'11/2' -> 5.5
'7/8' -> 0.875
'3' -> 3
'7.7' -> 7.7

I'm currently using this function, but I think it could be improved. It also doesn't handle numbers that are already in decimal representation

def mixedtofloat(txt):

    mixednum = re.compile("(\\d+) (\\d+)\\/(\\d+)",re.IGNORECASE|re.DOTALL)
    fraction = re.compile("(\\d+)\\/(\\d+)",re.IGNORECASE|re.DOTALL)
    integer = re.compile("(\\d+)",re.IGNORECASE|re.DOTALL)

    m = mixednum.search(txt)
    n = fraction.search(txt)
    o = integer.search(txt)

    if m:
        return float(m.group(1))+(float(m.group(2))/float(m.group(3)))
    elif n:
        return float(n.group(1))/float(n.group(2))
    elif o:
        return float(o.group(1))
    else:
        return txt

Thanks!

© Stack Overflow or respective owner

Related posts about python

Related posts about mixed