I want to use qDebug(), qInfo() and so on with a custom default floating point precision and number format.
Is there a way to define this globally?
Imagine this:
double num = 1.2;
qDebug() << "My floating point Number is: " << QString::number(num, 'f', 2);
//Output: My floating point Number is 1.20
Now I would like to avoid QString::number(num, 'f', 2) everytime I write a number and would much rather like to use a standard percision and format.
Formatting of a QDebug
stream can be controlled through QTextStream
manipulators. Therefore, you must call
qDebug() << fixed << qSetRealNumberPrecision(2);
in the beginning of your program.
Note, however, that the formatting state of qDebug()
may change later if some (not so carefully written) code sets required formatting and doesn't restore it to the previous state after completing its job.
EDIT
It turns out that the effect of QTextStream
manipulators (at least in combination with qDebug()
) is limited to the containing statement and doesn't persist. So, the best you can do is define your replacement of qDebug()
as follows:
#define myqDebug() qDebug() << fixed << qSetRealNumberPrecision(2)
and use it instead of qDebug()
:
double num = 1.2;
myqDebug() << "My floating point Number is: " << num << endl;
Output:
My floating point Number is: 1.20
You can't.
qDebug()
, qFatal()
, etc... return instances of the class QDebug
.
The issue is that the operator QDebug::operator<<(float f)
is a non virtual class member function.
You cannot define another without getting the compile error message
operator<< is ambiguous
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With