68

I am writing a program in Qt. I want to convert a double into a QString in C++.

1
  • @Macmade, I am new to QT and CPP. But i have a java code so i want to convert into cpp for qt application.
    – Nagaraju
    Commented May 9, 2011 at 18:26

5 Answers 5

113

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

double valueAsDouble = 1.2;
QString valueAsString = QString::number(valueAsDouble);
4
  • This one is annoying since precision is fixed. Commented Mar 5, 2016 at 11:13
  • 1
    CAUTION: That call may lead to loss of precision. I did that same call once and I got 6.84442e+06 from 6844418.0, for example. They were metric UTM coordinates, so that 10m loss was unacceptable. Please, do be careful depending on the application. I used std::stringstream ss; ss << std::setprecision( 12 ); ss << (double)value; How do I markdown code blocks in this thing? Commented Mar 6, 2017 at 12:09
  • @PauloCarvalho Use QLocale::FloatingPointShortest (available since Qt 5.7)
    – syockit
    Commented May 17, 2019 at 4:43
  • Note: For the 'g' and 'G' formats, the precision represents the maximum number of significant digits (trailing zeroes are omitted). For example 1.0 will be converted to "1"
    – kslavka
    Commented Jun 10, 2020 at 8:25
18

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

1
  • 2
    Not always. I need to convert to US system (48.1), and this would mess things. Commented Jul 23, 2014 at 14:27
17

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

0
9

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

1
  • According to the doc The conversion uses the default locale, the precision is also -1 by default instead of 6 for QString::number
    – ymoreau
    Commented Jan 5, 2018 at 16:14
4

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.