Decimals to fraction strings

Stuart D. Gathman stuart at bmsi.com
Tue May 16 13:33:48 EDT 2000


Scott wrote:

> Does anyone know of a way to convert decimal numbers to a string
> representation of the fractional value? For example:
> 0.5 = "1/2"
> or
> 1.125 = "1 1/8"

1) Convert to a fraction by counting places after the decimal:

    0.5 -> 5 / 10
    1.125 -> 1125 / 1000
    2.6 -> 26 / 10
    3.14156295 = 314159265 / 100000000

2) Divide top and bottom by their GCD (greatest common divisor):

    5 / 10 -> 1 / 2
    1125 / 1000 -> 9 / 8
    26 / 10 -> 13 / 5
    314159265 / 100000000 -> 62831853 / 20000000

3) If desired (I don't), convert to mixed notation when num > den by
finding quotient and remainder of num / den:

    9 / 8 -> 1 rem 1 -> 1 1/8
   13 / 5 -> 2 rem 3 -> 2 3/5
    62831853 / 20000000 -> 3 2831853/20000000






More information about the Python-list mailing list