Using mpq_t for aggregating currencies with wildly varying ranges

Donovan Hide donovanhide at gmail.com
Wed Apr 16 19:26:43 UTC 2014


Thanks! I'll analyse this deeply :-)

This is what I've got so far:

void format_rational(mpq_t r,char *result,unsigned long *length){
mpq_canonicalize(r);
mpz_t five,num,den;
mpz_init_set_ui(five,5);
mpz_init(num);
mpz_init(den);
mpq_get_num(num,r);
mpq_get_den(den,r);
mp_bitcnt_t m = mpz_scan1(den,0);
mp_bitcnt_t n = mpz_remove(den,den,five);
if (m>n){
mpz_ui_pow_ui(five,5,m-n);
mpz_mul(num,num,five);
}else{
mpz_mul_2exp(num,num,n-m);
}
char *temp = mpz_get_str (NULL, 10, num);
size_t len = strlen(temp);
*length=gmp_sprintf(result,"%.*s.%.*s %d %d
%Qu",len-m,temp,m,temp+len-m,m,len,r);
free(temp);
mpz_clear(five);
mpz_clear(num);
mpz_clear(den);
}

Just need to get the leading zero handling worked out. Realised adding
canonicalize() at the start trims trailing zeroes automatically. I think
this is going to be quite a powerful tool once it's up and running in MySql
:-)


More information about the gmp-discuss mailing list