Skip to content

Unexpected precision loss on parsing numbers #2002

@ivanstojic

Description

@ivanstojic

I'm seeing an unexpected result when parsing numbers from JSON, and how they parse to doubles. Sample source code:

#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>

using namespace rapidjson;

int main() {
    const char* json = "{\"thing\":-1.1030161663305387}";
    Document d;
    d.Parse(json);

    StringBuffer roundtripBuffer;
    Writer<StringBuffer> beforeWriter(roundtripBuffer);
    d.Accept(beforeWriter);

    Value& s = d["thing"];
    double thingVal = -1.1030161663305387;
    s.SetDouble(thingVal);

    StringBuffer nativeSetBuffer;
    Writer<StringBuffer> afterWriter(nativeSetBuffer);
    d.Accept(afterWriter);

    std::cout << json << std::endl;
    std::cout << roundtripBuffer.GetString() << std::endl;
    std::cout << nativeSetBuffer.GetString() << std::endl;
    return 0;
}

Output of this program is:

ivans@cram:~$ g++ simpledom.cpp && ./a.out
{"thing":-1.1030161663305387}
{"thing":-1.103016166330539}
{"thing":-1.1030161663305387}

The code takes a number (first line of output) and parses is from a JSON string, then takes that RapidJSON Document and reencodes it to string (second line). Then I reset the value of the property with a native float value, and use a writer to produce another JSON representation. That's the third line.

What I would have expected: all three lines to be the same.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions