Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Precision problem of cJSON_AddNumberToObject(); with double and float. #41

Open
ironengineer opened this issue Feb 23, 2017 · 1 comment

Comments

@ironengineer
Copy link

Question:
How can I add the double value only with given precision as provided 100.2 instead of 100.200000. Is it possible to generate the expected result below?

(When I gave the same number as float number = 100.2;, it generates: {"number value":100.199997} )
Example code:

double number = 100.2;
cJSON_AddNumberToObject(json, "number value", number);

Expected result:
{"number value":100.2}

Generated result:
{"number value":100.200000}

@ironengineer ironengineer changed the title cJSON_AddNumberToObject(); with double and float. Precision problem of cJSON_AddNumberToObject(); with double and float. Feb 23, 2017
@kbranigan
Copy link
Owner

The problem you're talking about is actually a problem with floating point numbers in computers in general. Unfortunately you are actually not able to put the value 0.2 accurately into a floating point number. The only way you can store that value is with a string value. (it's just how floats represent decimal numbers in binary, you can store 0.5, 0.25, 0.125, 0.0625, 0.03125 and so on but there's no way to create precisely 0.2 by adding these values together) Take a look at https://en.wikipedia.org/wiki/Single-precision_floating-point_format or http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/

Also, I'm not the author of this repo - you should post to https://github.com/DaveGamble/cJSON if you're interested in talking with the actual author.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants