MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / decimal_to_fraction

Function decimal_to_fraction

maths/decimal_to_fraction.py:1–52  ·  view source on GitHub ↗

Return a decimal number in its simplest fraction form >>> decimal_to_fraction(2) (2, 1) >>> decimal_to_fraction(89.) (89, 1) >>> decimal_to_fraction("67") (67, 1) >>> decimal_to_fraction("45.0") (45, 1) >>> decimal_to_fraction(1.5) (3, 2) >>> decimal_

(decimal: float | str)

Source from the content-addressed store, hash-verified

1def decimal_to_fraction(decimal: 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 >>> decimal_to_fraction(0)
20 (0, 1)
21 >>> decimal_to_fraction(-2.5)
22 (-5, 2)
23 >>> decimal_to_fraction(0.125)
24 (1, 8)
25 >>> decimal_to_fraction(1000000.25)
26 (4000001, 4)
27 >>> decimal_to_fraction(1.3333)
28 (13333, 10000)
29 >>> decimal_to_fraction("1.23e2")
30 (123, 1)
31 >>> decimal_to_fraction("0.500")
32 (1, 2)
33 """
34 try:
35 decimal = float(decimal)
36 except ValueError:
37 raise ValueError("Please enter a valid number")
38 fractional_part = decimal - int(decimal)
39 if fractional_part == 0:
40 return int(decimal), 1
41 else:
42 number_of_frac_digits = len(str(decimal).split(".")[1])
43 numerator = int(decimal * (10**number_of_frac_digits))
44 denominator = 10**number_of_frac_digits
45 divisor, dividend = denominator, numerator
46 while True:
47 remainder = dividend % divisor
48 if remainder == 0:
49 break
50 dividend, divisor = divisor, remainder
51 numerator, denominator = numerator // divisor, denominator // divisor
52 return numerator, denominator
53
54
55if __name__ == "__main__":

Callers 1

Calls 1

splitMethod · 0.80

Tested by

no test coverage detected