I used QString::number(doubleNumber, 'g' , 3) to get String representing the significant decimals up to 3.
The g format doesn't give 3 "significant decimals", it gives 3 "significant digits" - this includes digits both before (excluding leading 0's) and after the decimal. Have a read of https://en.wikipedia.org/wiki/Significant_figures for more info.
It works well in 99.9999% cases but for 14.25 instead of giving 14.25 it returns 14.3
14.3 is correct. The three significant digits there are 1, 4, and .3.
I know I could use QString::number(doubleNumber'f',3) ... Why is that
The reason the f format gives more decimals in your example, is that the f format interprets the precision parameter as a number of decimals, whereas g interprets it as a number of significant digits (which, as I mentioned above, includes digits before the decimal too).
This is documented in the table under QLocale::toString(), which QString::number() links to (and @JonB referenced above). See the "Meaining of precision column:
[image: 2f1ad327-50d1-40ae-a2f0-d5cf4ca0c35c.png]
and what to use instead?
If you specifically want "up to 3 decimals", as opposed to "exactly 3 decimals" (f) or "up to 3 significant digits" (g), then I suppose using f then trimming trailing 0 chars is one way to go.
Just one of many ways to do it:
const double doubleNumber = 14.25;
qDebug() << QString::number(doubleNumber,'f',3);
qDebug() << QString::number(doubleNumber,'g',3);
qDebug() << QString::number(doubleNumber,'f',3).remove(QRegularExpression(QStringLiteral("0+$")));
Outputs:
"14.250"
"14.3"
"14.25"
Cheers.