2

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.

2 Answers 2

4
>>> 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)
Sign up to request clarification or add additional context in comments.

Comments

3

Python has the fractions module.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.