QJsonObject insert QJsonValue(double) looses precision



  • Hi,

    I have a double value which i want to bring into a QJsonObject. But on inserting the QJsonValue into the QJsonObject the precision of the value changed. But why

    @
    double x = 23.2;
    QJsonObject obj;
    QJsonValue v = QJsonValue(x);
    obj.insert("value",v);

    qDebug() << x;
    qDebug() << v;
    qDebug() << obj;
    

    @

    returns:

    23.2
    QJsonValue(double, 23.2)
    QJsonObject({"value": 23.199999999999999})

    What's going wrong here. Can anybody help me pls?

    Thanks!


  • Moderators

    Hi, and welcome to the Qt Dev Net!

    There are two things you need to be aware of:

    Your loss of precision occured when you assigned 23.2 to x. A

    double, as defined by the "IEEE floating point standard":http://en.wikipedia.org/wiki/IEEE_floating_point, cannot store 23.2 precisely.

    The different outputs you saw is due to "roundings" that qDebug() did before displaying the text. All 3 values are actually the same.

    To check yourself, do this:
    @
    qDebug() << obj;
    qDebug() << obj.value("value");
    qDebug() << obj.value("value").toDouble();
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.