4

I have made class that convert QList<qreal> (very big list) to JSON string, but it generates a extra large text.

Here is code:

QJsonObject rootObject;
rootObject.insert("Test",0.05);
qDebug()<<QJsonDocument(rootObject).toJson(QJsonDocument::Compact);

And I have tried equal code:

QJsonObject rootObject;
rootObject.insert("Test",QString("0.05").toDouble());
qDebug()<<QJsonDocument(rootObject).toJson(QJsonDocument::Compact);

And debug ouptut is always:

{"Test":0.050000000000000003}

I want to get short output like this:

{"Test":0.05}

Is there way to fix QJsonDocument? Or make some decimals count rounding/limit?

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
IGHOR
  • 691
  • 6
  • 22
  • Why are you converting a double to a string and then back to a double? – TheDarkKnight Nov 05 '14 at 16:53
  • @Merlin069 because all my input data has come from double value that converted from QString. And it is a proof that bug is not in that toDouble conversion. – IGHOR Nov 05 '14 at 17:11
  • I see, since you missed the quotes around 0.05 passed into QString, I didn't realise that the input was originally a string. I've tested QVariant and that works, so you're right that the json conversion is the problem. It's not ideal, but you could write a string, instead of the double. – TheDarkKnight Nov 05 '14 at 17:30
  • Thanks for trying it. Yes I'll use strings if there is no solution for double. – IGHOR Nov 05 '14 at 17:32
  • What platform are you on? – TheDarkKnight Nov 05 '14 at 17:33
  • @Merlin069 Mac OS X Yosemite, and tested on Open Suse Linux, the same result. – IGHOR Nov 05 '14 at 18:01

1 Answers1

1

On OS X I tried the following: -

QVariant d(0.5);
QJsonValue val = QJsonValue::fromVariant(d);

qDebug() << val.toDouble();

This prints out 0.5, as expected.

However, I think the problem is due to floating point precision. QJSonDocument is representing the number as accurately as possible, but does not have a function to limit the number of decimal places represented, as is present in QString.

Though not ideal, if your really want 0.5 represented this way, you can write a string value instead of the double.

Community
  • 1
  • 1
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
  • Single value looks ok, but I need to get valid json string with names and values. So I used QJsonArray and QJsonDocument to convert all to string. Looks like it QJsonDocument problem only. – IGHOR Nov 05 '14 at 17:55
  • I just need to convert QJsonObject to valid JSON string. QJsonObject contains this doubles and output is to large. Some doubles converted correcty, but I have tested 0.5 and it always huge. – IGHOR Nov 05 '14 at 18:02
  • I think the problem is floating point precision and have updated the answer accordingly. – TheDarkKnight Nov 06 '14 at 09:11