Search code examples
c++boostfloating-pointboost-propertytree

C++ storing a float value in boost property tree


I'm trying to modify some library and I need to store a float value in a ptree. However when I retrieve the value it's different from what I've put in there. This doesn't happen with doubles. Example:

Ptree pt;

float f = 230518.391;
pt.put("float", f);
pt.put("double", (double) f)

cout << "f: " << f;
cout << "pt.float: " << pt.get<float>("float");
cout << "pt.double: " << pt.get<double>("double");

Output: f: 230518.391 pt.float: 230518.406 pt.double: 230518.391

What the hell is happening here?


Solution

  • Probably a combination of rounding "errors" & the compiler optimizing.. The rounding happens when the float is stored into the property tree..

    However when you store a double the rounding doesn't happen. Now at the line pt.put("double", (double) f) the compiler might optimize the "f" away, and put the literal there. So the compiler doesn't use the rounded value. Similar for the first cout cout << "f: " << f; Here too the float is optimized away and the literal is put in its place.

    EDIT: just tested it, can it be that the "rounded" value actually is "230518.906

    this site might help with converting those numbers :).