|
| 1 | +def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]: |
| 2 | + """ |
| 3 | + Return a decimal number in its simplest fraction form |
| 4 | + >>> decimal_to_fraction(2) |
| 5 | + (2, 1) |
| 6 | + >>> decimal_to_fraction(89.) |
| 7 | + (89, 1) |
| 8 | + >>> decimal_to_fraction("67") |
| 9 | + (67, 1) |
| 10 | + >>> decimal_to_fraction("45.0") |
| 11 | + (45, 1) |
| 12 | + >>> decimal_to_fraction(1.5) |
| 13 | + (3, 2) |
| 14 | + >>> decimal_to_fraction("6.25") |
| 15 | + (25, 4) |
| 16 | + >>> decimal_to_fraction("78td") |
| 17 | + Traceback (most recent call last): |
| 18 | + ValueError: Please enter a valid number |
| 19 | + """ |
| 20 | + try: |
| 21 | + decimal = float(decimal) |
| 22 | + except ValueError: |
| 23 | + raise ValueError("Please enter a valid number") |
| 24 | + fractional_part = decimal - int(decimal) |
| 25 | + if fractional_part == 0: |
| 26 | + return int(decimal), 1 |
| 27 | + else: |
| 28 | + number_of_frac_digits = len(str(decimal).split(".")[1]) |
| 29 | + numerator = int(decimal * (10**number_of_frac_digits)) |
| 30 | + denominator = 10**number_of_frac_digits |
| 31 | + divisor, dividend = denominator, numerator |
| 32 | + while True: |
| 33 | + remainder = dividend % divisor |
| 34 | + if remainder == 0: |
| 35 | + break |
| 36 | + dividend, divisor = divisor, remainder |
| 37 | + numerator, denominator = numerator / divisor, denominator / divisor |
| 38 | + return int(numerator), int(denominator) |
| 39 | + |
| 40 | + |
| 41 | +if __name__ == "__main__": |
| 42 | + print(f"{decimal_to_fraction(2) = }") |
| 43 | + print(f"{decimal_to_fraction(89.0) = }") |
| 44 | + print(f"{decimal_to_fraction('67') = }") |
| 45 | + print(f"{decimal_to_fraction('45.0') = }") |
| 46 | + print(f"{decimal_to_fraction(1.5) = }") |
| 47 | + print(f"{decimal_to_fraction('6.25') = }") |
| 48 | + print(f"{decimal_to_fraction('78td') = }") |
0 commit comments