Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you set the qDebug() floating point precision and number format globally?

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.

like image 504
FreddyKay Avatar asked Aug 25 '16 13:08

FreddyKay


2 Answers

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
like image 190
Leon Avatar answered Sep 27 '22 21:09

Leon


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

like image 24
UmNyobe Avatar answered Sep 27 '22 21:09

UmNyobe