Reputation: 8419
I would like to store a double
value in QJsonObject
and retrieve the same value later. However, the retrieved value is with lower precision.
Here is an example:
qDebug() << QJsonObject({{"number", 49.195502187}}).value("number").toDouble();
outputs 49.1955
, instead of 49.195502187
.
I have checked Why does qjsonvalue todouble conversion cause data loss?, but it is about conversion between data types and not relevant to my specific case.
How to retrieve the correct value?
Upvotes: 0
Views: 1561
Reputation: 98465
#include <QtCore>
int main() {
auto const value = 49.195502187;
auto const recovered = QJsonObject({{"number", value}}).value("number").toDouble();
Q_ASSERT(value == recovered);
}
Works for me. There's no precision loss. Generally speaking, code speaks better than words, so if you're saying that something happens, you better write a test case with an assertion to that effect, and only post the question if the assertion proves a problem. It also makes it very clear what your expectations are - there's no ambiguity in the code, as there would be in English (as long as you don't depend on undefined or implementation-defined behavior, that is).
Upvotes: 1
Reputation: 8419
The precision loss occurs only when the value is displayed. Internally the correct value is stored. To make sure it is like that, break the code down like this:
QJsonObject json({{"number", 49.195502187}});
double value = json.value("number").toDouble();
qDebug() << value;
Then use a debugger with a breakpoint set at qDebug() << value;
:
I would suggest you to use QString::number
in order to set the desired precision for the displayed value, e.g.:
qDebug() << QString::number(value, 'g', 14);
This will give you the value you have stored in the JSON:
49.195502187
Upvotes: 8