Decimals to fraction strings

François Pinard pinard at iro.umontreal.ca
Tue May 16 14:02:04 EDT 2000


"Stuart D. Gathman" <stuart at bmsi.com> writes:

> 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:
> 2) Divide top and bottom by their GCD (greatest common divisor):
> 3) If desired (I don't), convert to mixed notation when num > den by
> finding quotient and remainder of num / den:

Yet your suggestion is straightforward, it might not always yield the "best"
answer, because of the constraint put on the denominator to initially be
an exponent of 10.  It might be quite sufficient for the problem at hand.

If I had this problem, I would probably explore GNU Calc sources, as they
contain an algorithm for exactly this problem, that give better solutions.
For Calc users, this is command `c F' (or `calc-fraction').  Take a look
in the Calc manual for more information about how to choose precision.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list