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

fix: minimize the precision loss when dumping double to string #712

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 3 additions & 2 deletions include/crow/json.h
Original file line number Diff line number Diff line change
Expand Up @@ -1851,10 +1851,11 @@ namespace crow
} f_state;
char outbuf[128];
#ifdef _MSC_VER
sprintf_s(outbuf, sizeof(outbuf), "%f", v.num.d);
#define MSC_COMPATIBLE_SPRINTF(BUFFER_PTR, FORMAT_PTR, VALUE) sprintf_s((BUFFER_PTR), 128, (FORMAT_PTR), DBL_DECIMAL_DIG, (VALUE))
gittiver marked this conversation as resolved.
Show resolved Hide resolved
#else
snprintf(outbuf, sizeof(outbuf), "%f", v.num.d);
#define MSC_COMPATIBLE_SPRINTF(BUFFER_PTR, FORMAT_PTR, VALUE) sprintf((BUFFER_PTR), (FORMAT_PTR), DECIMAL_DIG, (VALUE))
gittiver marked this conversation as resolved.
Show resolved Hide resolved
#endif
MSC_COMPATIBLE_SPRINTF(outbuf, "%.*g", v.num.d);
char *p = &outbuf[0], *o = nullptr; // o is the position of the first trailing 0
f_state = start;
while (*p != '\0')
Expand Down
6 changes: 4 additions & 2 deletions tests/unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1038,11 +1038,13 @@ TEST_CASE("json::wvalue::wvalue(float)")

TEST_CASE("json::wvalue::wvalue(double)")
{
double d = 4.2;
double d = 0.036303908355795146;
json::wvalue value = d;

CHECK(value.t() == json::type::Number);
CHECK(value.dump() == "4.2");
auto dumped_value = value.dump();
CROW_LOG_DEBUG << dumped_value;
CHECK(std::abs(utility::lexical_cast<double>(dumped_value) - d) < numeric_limits<double>::epsilon());
} // json::wvalue::wvalue(double)

TEST_CASE("json::wvalue::wvalue(char const*)")
Expand Down