Search code examples
pythonfractions

python - decimal into fraction divided by 1


I need to convert a decimal into fraction even if it's divided by 1. I tried using fractions module, but it gives, say, 3 instead of 3/1, 5 instead of 5/1 etc. So I was wondering if there is any possibility to get this kind of fraction using fractions module or something else?


Solution

  • You can use string formatting to achieve what you want.

    from fractions import Fraction
    no = Fraction(3, 1)
    
    str_no = "{0}/{1}".format(no.numerator, no.denominator)
    print(str_no)