Converting a decimal string to mpq_t

Christian Calderon calderonchristian73 at gmail.com
Wed Apr 30 21:58:57 CEST 2025


I would just copy the decimals to a new buffer with enough space to add
"/10..." with enough trailing zeros. Then pass that buffer to mpq_set_str.
Here is an example.

#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <gmp.h>


int main(int argc, char **argv){
if(argc != 2){
printf("exactly one argument is required!\n");
return 1;
}

char *decimal_string = argv[1];
size_t decimal_length = strlen(decimal_string) - 2;
// A decimal string of length n, has n-2 significant digits, since it
starts with "0."
// Let b = n - 2. Then the denominator of the rational form is 10**b,
// or a "1" character followed by b "0" characters.
// The string version has a single "/" character in the middle.
// so the total length of the string version is b + 1 + 1 + b characters,
plus an extra bit
// for the null character.
char *fraction_buf = calloc(2*decimal_length + 3, 1);
memcpy(fraction_buf, decimal_string + 2, decimal_length);
fraction_buf[decimal_length] = '/';
fraction_buf[decimal_length+1] = '1';
memset(fraction_buf + decimal_length + 2, '0', decimal_length);
mpq_t rat;
mpq_init(rat);
mpq_set_str(rat, fraction_buf, 10);
mpq_canonicalize(rat);
printf("Canonical form of digits:\n");
mpq_out_str(stdout, 10, rat);
printf("\n");
return 0;
}





~ Christian Calderon


On Mon, Apr 28, 2025 at 1:41 PM Anders Andersson <pipatron at gmail.com> wrote:

> Good evening! I wanted to convert a simple decimal string such as
> "0.1" to an mpq_t but I can't find a way to do it even though an mpq_t
> should be able to represent every such number exactly in every base,
> except possibly NaN and Inf.
>
> Do I have to write my own parser or do you have any ideas? Have I
> missed something obvious?
>
> If I manage to summon the strength to write such a function, would it
> be a good idea to extend mpq_set_str to handle floating point input?
>
>
> // Anders
> _______________________________________________
> gmp-discuss mailing list
> gmp-discuss at gmplib.org
> https://gmplib.org/mailman/listinfo/gmp-discuss
>


More information about the gmp-discuss mailing list