w3resource

Python Math: Convert a float to ratio

Python Math: Exercise-24 with Solution

Write a Python program to convert a float to ratio.

Sample Solution:-

Python Code:

from fractions import Fraction
value = 4.2
print(Fraction(value).limit_denominator())

Sample Output:

21/5 

Flowchart:

Flowchart: Convert a float to ratio

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a python program to find the next previous palindrome of a specified number.
Next: Write a Python program for nth Catalan Number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Lambdas for Sorting:

>>> students = [{'name': 'John', 'score': 98}, {'name': 'Mike', 'score': 94}, {'name': 'Jennifer', 'score': 99}]
>>> sorted(students, key=lambda x: x['score'])
[{'name': 'Mike', 'score': 94}, {'name': 'John', 'score': 98}, {'name': 'Jennifer', 'score': 99}]