Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 561
markdozer Avatar asked Sep 07 '25 12:09

markdozer


2 Answers

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
like image 99
user2357112 supports Monica Avatar answered Sep 10 '25 04:09

user2357112 supports Monica


Just a workaround using regex :)

import re

result = str(800/600)
# result = str(900/600)

repeating_pair = re.escape(result.split('.')[1][:2])
check_within = result.split('.')[1][2:]

if re.match(repeating_pair, check_within):
    print("{:.2f}".format(float(result)))
else:
    print("{:.1f}".format(float(result)))

Output:

1.33

And for 900/600

1.5
like image 32
Nuhil Mehdy Avatar answered Sep 10 '25 03:09

Nuhil Mehdy