I was wondering how to convert a decimal into a fraction in its lowest form in Python.
For example:
0.25 -> 1/4
0.5 -> 1/2
1.25 -> 5/4
3
If you'd like to print a proper fraction, this little recipe should do:
from fractions import Fraction
def dec_to_proper_frac(dec):
sign = "-" if dec < 0 else ""
frac = Fraction(abs(dec))
return (f"{sign}{frac.numerator // frac.denominator} "
f"{frac.numerator % frac.denominator}/{frac.denominator}")
This will print as follows:
>>> dec_to_proper_frac(3.75)
>>> "3 3/4"