Convert fraction to float?

Though you should stear clear of eval completely. Perhaps some more refined version of:

num,den = s.split( '/' )
wh, num = num.split()
result = wh + (float(num)/float(den))

Sorry, meant to be num.split not s.split, and casts. Edited.


maybe something like this (2.6+)

from fractions import Fraction
float(sum(Fraction(s) for s in '1 2/3'.split()))

I tweaked James' answer a bit.

def convert_to_float(frac_str):
    try:
        return float(frac_str)
    except ValueError:
        num, denom = frac_str.split('/')
        try:
            leading, num = num.split(' ')
            whole = float(leading)
        except ValueError:
            whole = 0
        frac = float(num) / float(denom)
        return whole - frac if whole < 0 else whole + frac


print convert_to_float('3') # 3.0
print convert_to_float('3/2') # 1.5
print convert_to_float('1 1/2') # 1.5
print convert_to_float('-1 1/2') # -1.5

http://ideone.com/ItifKv

Tags:

Python

Parsing