Search code examples
stringtype-conversiongmp

how to convert mpf_class to String


Hello and sorry for my basic English. I'm trying to convert from mpf_class to a String. I know there is a function (get_str()) but it show me only digits and its exponent separated. I want to get the whole expression in a string. I tried using ostreamstring and it work but I want to know if there is another way to do that. Let me know if I made myself clear.

Basically what I did was:

std::ostringstream show;
mpf_class result, Afact,Bfact,Cfact;
result=Afact*Bfact/Cfact;
show << result;
ui->lineEdit_5->setText(QString::fromStdString(show.str()));

As you can see, I'm working in a QT project and I need to show the result in a QLineEdit and with ostreamstring it works. I just was wondering if there is a gmp function to do that. thanks


Solution

  • Not sure whether this can help you, but you can actually print an mpf_class object and use I/O manipulators on it as a typical float object.

    Here is my code

    #include <gmpxx.h>
    #include <iostream>
    #include <iomanip>
    
    int main(void) {
        mpf_class a;
        a = 3141592653589793.2;
    
        std::cout << a << std::endl;
        // Outputs 3.14159e+15
    
        std::cout << std::uppercase << std::showpos << std::setprecision(3) << a << std::endl;
        // Outputs +3.14E+15
    
    }
    

    Then you can use an std::ostringstream object instead of std::cout.

    Reference: https://gmplib.org/manual/C_002b_002b-Formatted-Output.html