How to get the precise value from QJsonObject?

67 Views Asked by At

I have made code below. i want correct value as 44112.25895 but result value is 44112.3 how can i fix this issue?

QJsonObject qj{ {"close", 44112.25895} };
qDebug() << qj;
QJsonValue qjv = qj.value("close");
qDebug() << qjv;
qDebug() << qjv.toDouble();

result is

QJsonObject({"close":44112.25895})

QJsonValue(double, 44112.3)

44112.3

2

There are 2 best solutions below

0
Pamputt On

As indicated by chehrlic in the comments, the default precision of qDebug() is not what you want. The Qt documentation says that the default precision is 6 digits.

You can adjust it using qSetRealNumberPrecision, like this:

 qDebug() << qSetRealNumberPrecision( 10 ) << qjv.toDouble();

If you want to set this precision only once, then you can define your own qDebug, such as:

#define qDebug10() qDebug() << qSetRealNumberPrecision(10)

and use it like this:

qDebug10() << qSetRealNumberPrecision( 10 ) << qjv.toDouble();
0
Nome On

It's only qDebug()'s representation issue.

Try this:

qDebug() << QString::number(qjv.toDouble(), 'f', 5);

You get: 44112.25895

Then, try:

qDebug() << QString::number(qjv.toDouble(), 'f', 30);

Now you get: 44112.258950000003096647560596466064

It's a floating point issue.