Search code examples
pythonprintingdecimalprecisionfractions

How to write Fraction as decimal with x DPs in Python?


What I'm looking for is a way to write out a python Fraction() type to an arbitrary number of decimal places. I've looked at the python docs for Fraction and Decimal, but I can't see any way to convert or to write out the Fraction.

So what I'm looking for is some way to print out

Fraction(5, 7)

as

0.7142857142857142857142857142857142857142857142857142

instead of

>> float(Fraction(5, 7))
0.7142857142857143

Specifying the number of DPs.


Solution

  • You can have arbitrary precision using the Decimal class.

    from fractions import Fraction
    from decimal import localcontext, Decimal
    
    def print_fraction(f, digits):
        assert(f.imag == 0)
    
        # Automatically reset the Decimal settings
        with localcontext() as ctx:
            ctx.prec = digits
            print(Decimal(f.numerator) / Decimal(f.denominator))
    
    f = Fraction(5, 7)
    print_fraction(f, 52)
    

    This will print 0.7142857142857142857142857142857142857142857142857143.