Skip to content

Commit

Permalink
Fix round-trip issue in float serialization using scientific notation (
Browse files Browse the repository at this point in the history
  • Loading branch information
fktn-k authored Dec 9, 2024
1 parent d049cad commit a5e73da
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 8 deletions.
8 changes: 4 additions & 4 deletions include/fkYAML/detail/conversions/to_string.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ inline enable_if_t<std::is_floating_point<FloatType>::value> to_string(FloatType
oss << v;
s = oss.str();

// If `f` is actually an integer, ".0" must be appended. The result would cause roundtrip issue otherwise.
// https://github.com/fktn-k/fkYAML/issues/405
const FloatType diff = v - std::floor(v);
if (diff < std::numeric_limits<FloatType>::min()) {
// If `v` is actually an integer and no scientific notation is used for serialization, ".0" must be appended.
// The result would cause a roundtrip issue otherwise. https://github.com/fktn-k/fkYAML/issues/405
const std::size_t pos = s.find_first_of(".e");
if (pos == std::string::npos) {
s += ".0";
}
}
Expand Down
8 changes: 4 additions & 4 deletions single_include/fkYAML/node.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10341,10 +10341,10 @@ inline enable_if_t<std::is_floating_point<FloatType>::value> to_string(FloatType
oss << v;
s = oss.str();

// If `f` is actually an integer, ".0" must be appended. The result would cause roundtrip issue otherwise.
// https://github.com/fktn-k/fkYAML/issues/405
const FloatType diff = v - std::floor(v);
if (diff < std::numeric_limits<FloatType>::min()) {
// If `v` is actually an integer and no scientific notation is used for serialization, ".0" must be appended.
// The result would cause a roundtrip issue otherwise. https://github.com/fktn-k/fkYAML/issues/405
const std::size_t pos = s.find_first_of(".e");
if (pos == std::string::npos) {
s += ".0";
}
}
Expand Down
2 changes: 2 additions & 0 deletions test/unit_test/test_serializer_class.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ TEST_CASE("SerializeClassTest_FloatNode", "[SerializeClassTest]") {
node_str_pair_t(2.10, "2.1"),
node_str_pair_t(3.14, "3.14"),
node_str_pair_t(-53.97, "-53.97"),
node_str_pair_t(23000000.0, "2.3e+07"),
node_str_pair_t(-23000000.0, "-2.3e+07"),
node_str_pair_t(std::numeric_limits<fkyaml::node::float_number_type>::infinity(), ".inf"),
node_str_pair_t(-1 * std::numeric_limits<fkyaml::node::float_number_type>::infinity(), "-.inf"),
node_str_pair_t(std::nan(""), ".nan"));
Expand Down

0 comments on commit a5e73da

Please sign in to comment.