Skip to content

JSON representation for floating point values has too many digits #1109

@grebenyukaa

Description

@grebenyukaa

The values of type "float" seem to be internally treated as values of type "double". This leads to an issue with their text representation. For example, the snippet below:

json j;
j["test"] = 0.42f;
std::cout << j.dump() << std::endl;

produces this json output:

{"test":0.41999998688697815}

I experimented a bit with float values, and found out, that a workaround, like that:

namespace nlohmann
{
    namespace detail
   {
        template<>
        inline char* to_chars<json::number_float_t>(char* first, char* last, json::number_float_t value)
        {
            std::ostringstream s;
            s << value;
            std::string buf = oss.str();
            return std::copy(buf.begin(), buf.end(), first);
        }
    }
}

can impove floats' representation, and produce the following json:

{"test":0.42}

I know, that floating point arithmetics is a sensitive topic, but I think, floats' representation in human-readable format should be improved, if possible.

  • Compiler: Microsoft Visual C++ 2015
  • Release: 3.1.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions