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

Feature/small float serialization #38

Merged
merged 2 commits into from
Mar 23, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1853,7 +1853,8 @@ class basic_json
recursively. Note that

- strings and object keys are escaped using escape_string()
- numbers are converted to a string before output using std::to_string()
- integer numbers are converted to a string before output using std::to_string()
- floating-point numbers are converted to a string using "%g" format

@param prettyPrint whether the output shall be pretty-printed
@param indentStep the indent level
Expand Down Expand Up @@ -1961,7 +1962,12 @@ class basic_json

case (value_t::number_float):
{
return std::to_string(m_value.number_float);
// 15 digits of precision allows round-trip IEEE 754 string->double->string
unsigned int sz = (unsigned int)std::snprintf(nullptr, 0, "%.15g", m_value.number_float);
std::vector<char> buf(sz + 1);
std::snprintf(&buf[0], buf.size(), "%.15g", m_value.number_float);
string_t formatted = buf.data();
return formatted;
}

default:
Expand Down
6 changes: 6 additions & 0 deletions test/unit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,12 @@ TEST_CASE("object inspection")
CHECK(s.find("42.23") != std::string::npos);
}

SECTION("dump and small floating-point numbers")
{
auto s = json(1.23456e-78).dump();
CHECK(s.find("1.23456e-78") != std::string::npos);
}

SECTION("dump and non-ASCII characters")
{
CHECK(json("ä").dump() == "\"ä\"");
Expand Down