Skip to content

Storing floats, and round trip serialisation/deserialisation diffs #572

Description

@cesaref

I'm interested in knowing what the best advice is for representing floats in json format - as far as I am aware, the spec includes double support, but not floats.

If I add a float value to a json container, and serialise it, the result gets extended to double, and hence the serialised representation is not what you would expect if floats were supported directly, but the API makes them look like they are a 1st class datatype, so we see stuff like this:

nlohmann::json test;

test["float_value"] = 0.1f;
test["double_value"] = 0.1;

std::ostringstream oss;

oss << test;

ASSERT_EQ(oss.str(), "{\"double_value\":0.1,\"float_value\":0.100000001490116}");

The reason this causes me issues is that I want to round trip some configuration - read floats parameters from json files, and test that if I were to serialise them, I get out what went in. I could carefully convert my floats to doubles myself, rather than relying on the assignment operator (and hence pass in only doubles which will be serialised correctly), but i'm wondering if there is a different/better way of achieving this?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions