nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
41.25k stars 6.57k forks source link

Is float valid number been limited? #4322

Closed designerMichael closed 3 months ago

designerMichael commented 3 months ago

Description

i have the code snipet as below:

std::string str_params = "{\"rr\": 0.03626268729567528, \"r2\": 501954.03626}";
  json dis_json;
  std::istringstream d_s(str_params);
  d_s >> dis_json;
  float rr = dis_json["rr"].get<float>();
  float r2= dis_json["r2"].get<float>();

  LOG(INFO) << "r2 info: " << dis_json["r2"] << ", " << r2;
  LOG(INFO) << "rr info: " << dis_json["rr"] << ", " << rr;

the output info is : r2 info: 501954.03626, 501954 rr info: 0.03626268729567528, 0.0362627

the problem is why the r2 parse to integer? how can i fix it ? thanks very much for support it.

Reproduction steps

run the code as descritption, can see the output info.

Expected vs. actual results

r2 is float number, as "501954.03626" not "501954"

Minimal code example

No response

Error messages

No response

Compiler and operating system

mac and cmake.

Library version

3.11.3

Validation

nlohmann commented 3 months ago

I think this is an issue in the log function. Using printf is fine:

std::string str_params = "{\"rr\": 0.03626268729567528, \"r2\": 501954.03626}";
json dis_json;
std::istringstream d_s(str_params);
d_s >> dis_json;
float rr = dis_json["rr"].get<float>();
float r2 = dis_json["r2"].get<float>();

std::printf("r2 info: %f\n", r2);
std::printf("rr info: %f\n", rr);

Output:

r2 info: 501954.031250
rr info: 0.036263
designerMichael commented 3 months ago

thank you for your answer. but i still have the other question: why the r2 info is :"501954.031250". not the same as json string "501954.03626"

designerMichael commented 3 months ago

i add the test code as below:

   float r2= dis_json["r2"].get<float>();
    std::string str_r2 = std::to_string(r2);
    std::printf("str_r2 =%s\n",str_r2.c_str());

the output is : str_r2 =501954.031250 it seems that the get<float>() changes floating-point precision ? how can i fix it ? if it use on the algorithm, different precision caused inconsistent results.

gregmarr commented 3 months ago

Yes, if you use float, you lose precision. Don't do that if you want the precision, use double.

designerMichael commented 3 months ago

thank you very much for your answer, it work for me.