Convert a double to a QString

C++Qt

C++ Problem Overview


I am writing a program in QT. I want to convert a double into a Qstring in C++.

C++ Solutions


Solution 1 - C++

Use QString's number method (docs are here):

double valueAsDouble = 1.2;
QString valueAsString = QString::number(valueAsDouble);

Solution 2 - C++

Instead of QString::number() i would use QLocale::toString(), so i can get locale aware group seperatores like german "1.234.567,89".

Solution 3 - C++

Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...) function. For instance, I wanted 3 decimal places:

double value = 34.0495834;
QString strValue = QString::number(value, 'f', 3);
// strValue == "34.050"

The 'f' specifies decimal format notation (more info here, you can also specify scientific notation) and the 3 specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number function can be found here in the QString documentation

Solution 4 - C++

You can use arg(), as follow:

double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);

This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision

Solution 5 - C++

Check out the documentation

Quote:

> QString provides many functions for > converting numbers into strings and > strings into numbers. See the arg() > functions, the setNum() functions, the > number() static functions, and the > toInt(), toDouble(), and similar > functions.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNagarajuView Question on Stackoverflow
Solution 1 - C++KristianView Answer on Stackoverflow
Solution 2 - C++LarsView Answer on Stackoverflow
Solution 3 - C++yanoView Answer on Stackoverflow
Solution 4 - C++Tarek.MhView Answer on Stackoverflow
Solution 5 - C++jwdView Answer on Stackoverflow