Jsoncpp not reading exponents correctly

587 views Asked by At

I am working with json in c++ and decided to try out Jsoncpp. In my json I have some values that are in scientific notation and contain negative exponents such as 4.0e-06. When I go to parse this json string I get weird results. The library seems to work fine on positive exponents but fails when a negative sign appears.

Below is an example of the code I was using to test this json string.

#include "json/json.h"
#include <iostream> 
#include <string>

using namespace std;

int main(){

    string json_example = "{\"test\":4.0e-06, \"test2\":0.000004\"}";

    Json::Value json;
    Json::Reader reader;
    bool parsed = reader.parse(json_example, json, false);

    cout << json.toStyledString() << endl;  


}

And this is the output I receive.

{
   "test" : 3.9999999999999998e-06,
   "test2" : 3.9999999999999998e-06
}

I cannot tell if this is a bug in the library or if I am doing something wrong. I have tried using older versions of Jsoncpp and still arrived at the same issue.

Thanks

1

There are 1 answers

2
Sga On

It's not JsonCpp's fault, just an issue with representing that number in double format. You can check it yourself:

double a, b, c, d, e, f;
a = json["test"].asDouble(); // 3.9999999999999998e-006
b = json["test2"].asDouble(); // 3.9999999999999998e-006
c = boost::lexical_cast<double>("4.0e-06"); // 3.9999999999999998e-006
d = boost::lexical_cast<double>("0.000004"); // 4.0000000000000007e-006 (!)
sscanf("4.0e-06", "%lf", &e); // 3.9999999999999998e-006
sscanf("0.000004", "%lf", &f); // 3.9999999999999998e-006

...But strangely enough, when I converted the JSON back to string I got this:

std::string test = json.toStyledString();

//{
//   "test" : 4.000000000000000e-006,
//   "test2" : 4.000000000000000e-006
//}