Python- Convert a mixed number to a float
- by user345660
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!