Examples of QString::number

Some examples of a very useful Qt function: QString::number. This function is helpful in converting double/float to string. QString, to be more precise 😉

QString::number has got 3 parameters:

  • double n – number, which will be converted
  • char format = ‚g – format: available formats are f, e, E, g, G. Default is ‚g’:
  • int precision = 6 – precision.

Let me show some examples. On the end of each line is a output from console:


//f - float
QString::number(3.14159265359, 'f', 0); //3
QString::number(3.14159265359, 'f', 1); //3.1
QString::number(3.14159265359, 'f', 2); //3.14
QString::number(3.14159265359, 'f', 15);//3.141592653590000

//e - exponential notation
QString::number(3.14159265359, 'e', 15); //3.141592653590000e+00
QString::number(3.14159265359, 'E', 15); //3.141592653590000E+00

//g/G - "general" - in this case: "f"
QString::number(3.14159265359, 'g', 0); //3
QString::number(3.14159265359, 'g', 1); //3
QString::number(3.14159265359, 'g', 2); //3.1
QString::number(3.14159265359, 'g', 15); //3.14159265359

QString::number(3.14159265359, 'G', 2); //3.1
QString::number(3.14159265359, 'G', 15); //3.14159265359

//g/G - "general" - in this case: "e/E"
QString::number(2.5e+5, 'g', 0); //2e+05
QString::number(2.5e+5, 'g', 1); //2e+05
QString::number(2.5e+5, 'g', 2); //2.5e+05
QString::number(2.5e+5, 'g', 15); //250000

QString::number(2.5e+5, 'G', 2); //2.5E+05
QString::number(2.5e+5, 'G', 15); //250000

//comparision with f and e/E:
QString::number(2.5e+5, 'f', 2); //250000.00

QString::number(2.5e+5, 'e', 15); //2.500000000000000e+05
QString::number(2.5e+5, 'E', 2); //2.50E+05

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *