QString QString::number(double n, char format = ‘g’, int precision = 6) returns a string equivalent of the number n, formatted according to the specified format and precision.
Let’s see the following example.
There are 3 double values x, y, z.
We want to return the result of the following equation:
(x / z) * (5.961 / y)
We also want to ask the user to set the desired precision of the result.
Here is how I do with Qt.
You can also Fork the complete qt project from my GitHub.
* note = there are many ways to solve this issue, much simpler, but this time I want to demonstrate how we do in Qt.
// (c) Roland Ihasz - https://github.com/lnrsoft
int main(int argc, char* argv)
QCoreApplication a(argc, argv);
double x = 1.190;
double z = 6.634;
double y = 3.398;
double result = (x / z) * (5.961 / y);
std::cout << "\nEnter the required precision of the result: ";
std::cin >> precision;
QString resultstring = QString::number(result, 'g', precision);
std::cout << "\n1.In this case the output is a double value."
std::cout << "The result by the compiler default setting is: "
<< result << "\n" << std::endl;
std::cout << "2. Using the QString::number member function."
std::cout << "The result when we set the precision to "
<< precision << " is: " << qPrintable(resultstring)
<< "\n" << std::endl;
* using qPrintable to remove qoutes from the output
In member functions where an argument format can be specified (e.g., arg(), number()), the argument format can be one of the following:
e format as [-]9.9e[+|-]999
E format as [-]9.9E[+|-]999
f format as [-]9.9
g use e or f format, whichever is the most concise
G use E or f format, whichever is the most concise
A precision is also specified with the argument format. For the ‘e’, ‘E’, and ‘f’ formats, the precision represents the number of digits after the decimal point. For the ‘g’ and ‘G’ formats, the precision represents the maximum number of significant digits (trailing zeroes are omitted).
How to return a string equivalent of the number n using Qt was written by Roland Ihasz>, you can modify or distribute. You can do anything you want with this software, just don’t say you wrote it.
More info on doc.qt.io