Reputation: 1
When working on python, I was able to convert a fraction to a decimal where the user would input a numerator, then a denominator and then the n/d = the result
(fairly simple). But i can't work out how to convert a decimal into a fraction. I want the user to input any decimal ( ie 0.5
) and then find the simplest form of x (1/2)
. Any help would be greatly appreciated. Thanks.
Upvotes: 0
Views: 474
Reputation: 6736
Use the fractions
module.
from fractions import Fraction
f1 = Fraction(14, 8)
print(f) # Output: 7/4
print(float(f)) # Output: 1.75
f1 = Fraction(1.75)
print(f) # Output: 7/4
print(float(f)) # Output: 1.75
It accepts both pairs of numerator/denominator as well as float decimal numbers to construct a Fraction object.
Upvotes: 1