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

Floating point precision lost #345

Closed
nickvkaam opened this issue Oct 29, 2016 · 3 comments
Closed

Floating point precision lost #345

nickvkaam opened this issue Oct 29, 2016 · 3 comments

Comments

@nickvkaam
Copy link

nickvkaam commented Oct 29, 2016

Input:

json data;
data["number"] = 11.4f;

output:

std::string dataString = data.dump();

result:

{
    "number": 11.3999996185303
}
@FabianoGK
Copy link

That is because you cannot represent 11.4 as a single-precision floating-point number. Take a look into ExploringBinary - Floating Point Converter.

Here is an example having the literal number on different precisions:

Input:

json data;
data["number-float"] = 11.4f;
data["number-double"] = 11.4;
data["number-long-double"] = 11.4l;

Output:

std::string dataString = data.dump();

Result:

{
    "number-double":11.4,
    "number-float":11.3999996185303,
    "number-long-double":11.4
}

@phoenixchinar
Copy link

You need to use decimal floating point to solve this issue. Normal float, double, and long double are based on a base of 2 and cannot represent all base 10 floating point numbers accurately. gcc has decimal32, decimal64 and decimal128 classes as well as underlying C types defined to address this.
In your compiler try this
if((0.1+0.2)==0.3)
std::cout<<"true"<<endl;
else
std::cout<<"false"<<endl;

You will need to change the underlying types, as the library serializes the underlying types accurately.

@nlohmann
Copy link
Owner

nlohmann commented Nov 2, 2016

Can this ticket be closed?

@nlohmann nlohmann added the state: please discuss please discuss the issue or vote for your favorite option label Nov 2, 2016
@nlohmann nlohmann removed the state: please discuss please discuss the issue or vote for your favorite option label Nov 11, 2016
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

4 participants