Convert fraction to float?

2019-01-11 23:07发布

Kind of like this question, but in reverse.

Given a string like 1, 1/2, or 1 2/3, what's the best way to convert it into a float? I'm thinking about using regexes on a case-by-case basis, but perhaps someone knows of a better way, or a pre-existing solution. I was hoping I could just use eval, but I think the 3rd case prevents that.

9条回答
淡お忘
2楼-- · 2019-01-11 23:45
def fractionToFloat(fraction):

    num = 0
    mult = 1

    if fraction[:1] == "-":
        fraction = fraction[1:]     
        mult = -1

    if " " in fraction:
        a = fraction.split(" ")
        num = float(a[0])
        toSplit = a[1]
    else:
        toSplit = fraction

    frac = toSplit.split("/")
    num += float(frac[0]) / float(frac[1])

    return num * mult

It can also handle "2 1/1e-8", "-1/3" and "1/5e3".

查看更多
Luminary・发光体
3楼-- · 2019-01-11 23:46

That might be a dirty workaround, but you could convert spaces to a + sign to solve the 3rd case (or to a - if your fraction is negative).

查看更多
该账号已被封号
4楼-- · 2019-01-11 23:50

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.

查看更多
登录 后发表回答