1

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

EMG
  • 11
  • 2

1 Answers1

1

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
//}
Sga
  • 3,608
  • 2
  • 36
  • 47
  • I see, I will try playing around with this a bit more and see if I can get the same output as you. Good to know its not the library at fault though. Thanks for your help. – EMG Jun 22 '15 at 14:00
  • 1
    You may consider [RapidJSON](http://stackoverflow.com/a/29878756/833188), which addresses this issue – Sga Jun 22 '15 at 14:01