Search code examples
c++decimalgmp

GMP: how to write a number as a decimal value?


I have an mpq_class instance, and I want to display it as a decimal value, rather than a fraction.

mpq_class nb = 1.75;
cout << nb << endl;

Output:

7/4

How can I output 1.75 rather than 7/4?


Solution

  • Easiest approach would probably be to convert to mpf_class, e.g. cout << mpf_class(nb) << endl;. You might need to explicitly set the output precision to avoid printing out garbage from floating point errors though.