How to convert a decimal number into fraction?

前端 未结 4 674
夕颜
夕颜 2020-11-28 04:35

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         


        
4条回答
  •  感动是毒
    2020-11-28 05:01

    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"
    

提交回复
热议问题