karpanai
karpanai

Reputation: 235

Python - Parse float string to an integer

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

Answers (2)

Tim Pietzcker
Tim Pietzcker

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

eumiro
eumiro

Reputation: 212835

Python has the fractions module.

>>> import fractions
>>> fractions.Fraction('0.75')
Fraction(3, 4)

Upvotes: 3

Related Questions