Question: I was wondering how to convert a decimal into a fraction in its lowest form in Python.

For example:

```
0.25  -> 1/4
0.5   -> 1/2
1.25  -> 5/4
3     -> 3/1

```

Answer: 
To expand upon Martijn Pieters excellent answer with an additional option due to the imprecision inherent with more complex floats. For example:

```
>>> f = 0.8857097
>>> f.as_integer_ratio()
(1994440937439217, 2251799813685248)          # mathematically wrong
>>> Fraction(f)
Fraction(1994440937439217, 2251799813685248)  # same result but in a class
>>> Fraction(f).limit_denominator()
Fraction(871913, 984423)                      # still imprecise

```

The mathematical result desired was `8857097/10000000` which can be achieved by casting to a string and then manipulating it. 

**Edited Response**

I found a much simpler way to resolve the accuracy issue.

```
>>> Fraction(str(f))
Fraction(8857097, 10000000)

```

Casting as to a string also allows for accurate Decimal instances

```
>>> Decimal(f).as_integer_ratio()
(1994440937439217, 2251799813685248)
>>> Decimal(str(f)).as_integer_ratio()
(8857097, 10000000)

```

**Original Response**

```
def float_to_ratio(flt):
    if int(flt) == flt:        # to prevent 3.0 -> 30/10
        return int(flt), 1
    flt_str = str(flt)
    flt_split = flt_str.split('.')
    numerator = int(''.join(flt_split))
    denominator = 10 ** len(flt_split[1])
    return numerator, denominator

```

Now let's test it:

```
>>> float_to_ratio(f)
(8857097, 10000000)      # mathematically correct

```

I will note that this kind of fraction precision is not optimized and will usually not be needed, but for completeness it is here. This function doesn't simplify the fraction, but you can do additional processing to reduce it: 

```
>>> n = 0.5
>>> float_to_ratio(n)
(5, 10)
>>> Fraction(*float_to_ratio(n))
Fraction(1, 2)

```
One of the easiest way is to use `as_integer_ratio()` like this.

```js
b = 0.125

b.as_integer_ratio()

# Output as Tuple(1, 8).Numerator as 1 & Denominator as 8
```