Search code examples
pythonpython-3.xmathfloating-pointfractions

About Fraction class in py3


Is there is a way to find the number at kth position after the decimal point in float representation of a fraction? k is up to 10^6. I tried converting float(Fraction) to str, it didn't give me desired precision.


Solution

  • You are looking for the decimal module in Python (comes out of the box with Python).

    from decimal import *
    
    division = 5 / 3
    print(division)  # 1.6666666666666667
    
    getcontext().prec = 6
    division = Decimal(5) / Decimal(3)
    print(division)  # 1.66667