QString formatting for rounding a decimal number
-
wrote on 7 Mar 2022, 07:19 last edited by
I've following code for rounding
myVal
to6
decimal places i.e0.314568
QString myVal ="0.3145678"; qDebug()<<"Ans=" << QString::asprintf("%10.6f",myVal);
It says
no member named 'asprintf' in 'Qstring'
. Can someone help me how to do it? -
wrote on 7 Mar 2022, 07:46 last edited by ChrisW67 3 Aug 2022, 02:41
However, the format specifier "%10.6f" requires a numeric value argument (usually a float or double) and you are feeding it a string. Your line compiles with a warning (at least with my compiler) and does something undefined as a result
There is a difference between rounding a numeric value at 6 decimal places, and simply displaying it in human readable form rounded to 6 decimal places. Which do you want?
#include <QCoreApplication> #include <QDebug> #include <QString> #include <cmath> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString myVal ="0.3145678"; double value = myVal.toDouble(); qDebug()<<"Original string =" << myVal; qDebug()<<"Original value =" << QString::asprintf("%10.7f", value); qDebug()<<"Rounded display =" << QString::asprintf("%10.6f", value); // Round the actual value value = std::round(value * 1e6) / 1e6; qDebug()<<"Rounded value =" << QString::asprintf("%10.7f", value); qDebug()<<"Rounded display =" << QString::asprintf("%10.6f", value); // Your line qDebug()<<"Ans=" << QString::asprintf("%10.6f",myVal); return 0; }
The warning
../untitled/main.cpp: In function ‘int main(int, char**)’: ../untitled/main.cpp:25:49: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘QString’ [-Wformat=] 25 | qDebug()<<"Ans=" << QString::asprintf("%10.6f",myVal); | ~~~~~^ | | | double
Output
Original string = "0.3145678" Original value = " 0.3145678" Rounded display = " 0.314568" Rounded value = " 0.3145680" Rounded display = " 0.314568" Ans= " 0.000000"
1/2