开发者

Is there a Python module where I could easily convert mixed fractions into a float?

开发者 https://www.devze.com 2023-04-03 20:46 出处:网络
I\'m just wondering if I could easily convert a mixed number (entered as a number or a string) into a floating point number or an integer. I\'ve looked at the fractions module but it seems like it cou

I'm just wondering if I could easily convert a mixed number (entered as a number or a string) into a floating point number or an integer. I've looked at the fractions module but it seems like it couldn't do what I want, or I didn't read well.

Just wanted to know if something already exists before I write my own function开发者_StackOverflow. Here's what I'm looking for, btw:

convert(1 1/2)

or

convert('1 1/2')

Thanks.


The built-in Fraction class does not appear to support mixed fractions like you have, but it wouldn't be too hard to split them up on the space. For example, 1 + fractions.Fraction('1/2') or a very simplistic

def convert(f):
    whole, frac = f.split()
    return int(whole) + fractions.Fraction(frac)


I wrote the Mixed class to extend fractions to do just that. Source is here.

>>> float(Mixed('6 7/8'))
6.875
>>> float(Mixed(1,1,2)) # 1 1/2
1.5
0

精彩评论

暂无评论...
验证码 换一张
取 消