QString::number(14.24,'g',3) returns 14.3 ?
-
I used QString::number(doubleNumber, 'g' , 3) to get String representing the significant decimals up to 3.
It works well in 99.9999% cases but for 14.25 instead of giving 14.25 it returns 14.3
Why is that and what to use instead?I know I could use QString::number(doubleNumber'f',3) and manually remove trailing zeros but why ?
-
@Seb-Tur
I don't know about your cases where you say it "works", but where doesg
format say it produces 3 significant decimals? It does not. See https://doc.qt.io/qt-6/qlocale.html#toString-8'g' use 'e' or 'f' format, whichever is more concise maximum number of significant digits (trailing zeroes are omitted)
The precision is "maximum number of significant digits".
-
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 are1
,4
, and.3
.I know I could use
QString::number(doubleNumber'f',3)
... Why is thatThe reason the
f
format gives more decimals in your example, is that thef
format interprets the precision parameter as a number of decimals, whereasg
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: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 usingf
then trimming trailing0
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.