How to use QTextStream setprecision
-
wrote on 7 Feb 2017, 16:40 last edited by tomy 2 Jul 2017, 16:42
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?
-
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?
-
wrote on 7 Feb 2017, 17:03 last edited by tomy 2 Jul 2017, 17:09
Thanks for the help.
-
wrote on 14 Feb 2017, 17:12 last edited by
This does not work exactly as C++ setprecision(int).
-
wrote on 14 Feb 2017, 17:39 last edited by VRonin
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))
-
wrote on 14 Feb 2017, 17:47 last edited by
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!
-
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))