How to use QTextStream setprecision



  • Hi all,

    Consider a small program in which the user each time enters a floating point number less than 1. We want to show that number in a lineEdit with that precision.

    This is its code in C++: (just for using setprecision)

       long double d = 0.12345678901;
        string s;
    stringstream ss;
    
    ss << setprecision(16);
    ss << d;
    ss >> s;
        cout << s.length() - 2 << endl;
    

    I tried to use its Qt equivalent like this:

    QString s;
    QTextStream ss(&s);
    long double d = 0.9254178963;
    
    ss << setprecision(16);
             ss << d;
             ss >> s;
             ss << QString::number(d, 'f', s.length());
    lineEdit -> setText(s);
    

    I got this error:

    'setprecision' was not declared in this scope
    ss << setprecision(16);

    How to solve it please?


  • Qt Champions 2016



  • Thanks for the help.



  • This does not work exactly as C++ setprecision(int).



  • This does not work exactly as C++ setprecision(int).

    it behaves as: /*stringstream*/ ss << fixed << setprecision(16)

    as explained here: https://forum.qt.io/topic/75939/how-to-search-for-a-specific-character-in-a-qstring/26

    int guessPrecision(double val){
        double junk;
        int precision = 0;
        for(;!qFuzzyIsNull(std::modf(tester,&junk));++precision)
            val*=10.0;
        return precision;
    }
    

    now you can use:
    ss->setRealNumberPrecision(guessPrecision(d))



  • I'm aware of the prior one. I just was thinking about a better solution.
    I used it and it showed 0.000 as result!

     QString s;
     QTextStream ss(&s);
     double d = 0.00001;
     ss << qSetRealNumberPrecision(16);
     ss << d;
     int precision = s.length()-2;
     s.clear();
     ss << QString::number(d, 'f', precision);
    

    By now, qFuzzy is the best choice!



  • @VRonin

    it behaves as: /*stringstream*/ ss << fixed << setprecision(16)

    Yes, unfortunately.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.