Search code examples
pythonroundingfractions

Round to two decimal places only if repeating python


I was wondering if anybody knew of a quick way in python to check and see if a fraction gives a repeating decimal.

I have a small function that takes in two numbers and divides them. If the quotient is a repeating decimal I would like to round to 2 decimal places and if the quotient is not repeating I would like to round to just one

Example:

800/600 = 1.33333333333333 which would equal 1.33

900/600 = 1.5 would stay as 1.5

I know that I need to use the two statements for the two types of rounding

output = "{:.2f}".format(float(num))
output = "{:,}".format(float(num))

but I am having trouble with the if statement to direct to one or the other.

Can anybody help with some insight?


Solution

  • Use the fractions module, which implements exact rational arithmetic:

    import fractions
    
    # fractions.Fraction instances are automatically put in lowest terms.
    ratio = fractions.Fraction(numerator, denominator)
    

    You can then inspect the denominator of the result:

    def is_repeating(fraction):
        denom = fraction.denominator
        while not (denom % 2):
            denom //= 2
        while not (denom % 5):
            denom //= 5
        return denom != 1