首页 > 解决方案 > String that represents float to fraction

问题描述

Im trying to handle a string like this:

s = '1/2.05'

When I try to parse it into a Fraction:

Fraction(s)

I am obtaining:

ValueError: ("Invalid literal for Fraction: u'1/2.05'", u'occurred at index 3')

I also tried:

Fraction(s.split('/')[0], s.split('/')[1])

But with error too:

TypeError: ('both arguments should be Rational instances', u'occurred at index 3')

How would the correct parsing be?

Thank you all in advance!

标签: pythonstringpython-2.7floating-pointfractions

解决方案


问题在于分数和浮点数不会混合,因此您不能对直接在分数中隐藏浮点数的字符串进行类型转换。

但是不要为此使用 eval 。
尝试分别处理分子和分母。(您可以使用浮点数,但直接在字符串上调用 Fraction 会更精确,从而避免精度问题。)

from fractions import Fraction
s = '1/2.05'
numerator, denominator =  s.split('/')
result = Fraction(numerator)/Fraction(denominator)
print(result)

推荐阅读