Reputation: 235
I want to convert a string like "0.75" into 3/4. Do python has any builtin function for this.
I know i can convert it using float("0.75") to get a float value. But I need only integer number without loosing resolution.
I can write a function like multiplying it by 100, so I will get 75/100, but still how to evaulate to 3/4. Any idea would be much appreciated.
Upvotes: 2
Views: 983
Reputation: 336128
>>> from fractions import Fraction
>>> Fraction(0.75)
Fraction(3, 4)
See the docs.
One caveat: Non-binary fractions (i.e. fractions derived from floating point numbers that cannot be represented accurately in binary, like 0.9
) may yield surprising results unless you pass the string representation of the float
:
>>> Fraction(0.9)
Fraction(8106479329266893, 9007199254740992)
>>> Fraction("0.9")
Fraction(9, 10)
Upvotes: 4