Elmi
Elmi

Reputation: 6203

Format QString with fixed number of digits

When using sprintf() when I want to format a number with a fixed number of digits, I have to use format strings like "%.3f" or "%2d". Now the Qt-manual says, I have to use QStrings::arg()-function instead of sprintf():

QString("%1").arg(QString::number(1.3));

So how do I specify the number of digits to be shown in resulting string? Thanks :-)

Upvotes: 1

Views: 8921

Answers (1)

cbuchart
cbuchart

Reputation: 11555

QString::arg

You can specify the formatting with QString::arg like:

  • %.3f: QString("%1").arg(1.3, 0, 'f', 3): where the second argument is the field-width (minimum width of the resulting string, 0 here), the third is the format of the number, (in this case f means use no scientific notation), and the fourth is the precision (3 number of decimal places).
  • %2d: QString("%1").arg(42, 2).

Note: When using QString::arg you must be careful on using the adequate data type. For example, if you want to format the number 50 with one zero decimal, you must use QString("%1").arg(50.0, 0, 'f', 1). If you use QString("%1").arg(50, 0, 'f', 1) instead (note 50 is an integer), code won't compile due to a conflict of arguments.

This is the preferred way to do it in Qt, specially if the formatting string has to be localized. One of the main reasons is that the placeholders for values have an index (%1, %2...), allowing them to be in any order in the string and keeping their semantics (you may need to change order in some languages).. When using sprintf-like functions the order of the arguments matters.

QString::asprintf

Nevertheless, and though not recommended in new Qt code, you can use the sprintf-like QString::asprintf (do not use QString::sprintf which is deprecated). For example, QString::asprintf("%.3f", 1.3).

Upvotes: 1

Related Questions