initialize a rational from a decimal string

Zimmermann Paul Paul.Zimmermann at
Tue Mar 12 13:10:49 CET 2013


> I'm looking for a way to initialize a rational from a decimal string. I
> thought it might be a common task but I don't see any function which
> would do this. Is there such a function?
> Examples:
> 0.97 => 97/100
> 1.5 => 3/2
> 3.89e100 => 389/1
> What I do now is parse the three parts of the decimal (XXX.YYYeZZZ) and
> then manually assemble the bits. This involves a lot of calculations
> however, in particular that fractional part as I need to loop over the
> numbers multiplying by 10. Is there a better way?

since internally GMP works with radix-2 floating-point numbers, there is no
better way. For example 0.97 is not representable exactly in binary, thus as
soon as you parse it as a mpf number, it will be rounded.

For numbers which are representable exactly in binary like 1.5, you can use
mpf_set_str then mpq_set_f.

Paul Zimmermann

More information about the gmp-discuss mailing list