diff options
author | Misha Ivkov <misha.ivkov@10gen.com> | 2019-06-11 17:02:48 -0400 |
---|---|---|
committer | Misha Ivkov <misha.ivkov@10gen.com> | 2019-06-11 17:03:12 -0400 |
commit | cad3a84e198e0851c7a8dd49d365ea1ce5cada50 (patch) | |
tree | f8d3190c3a5c0434c40641e0f278efc245f08360 /src/mongo/util | |
parent | 95975c0e9c725ef86ef2fe6a8f5372e8a3f219d3 (diff) | |
download | mongo-cad3a84e198e0851c7a8dd49d365ea1ce5cada50.tar.gz |
SERVER-41271 allow logging doubles with arbitrary precision
Diffstat (limited to 'src/mongo/util')
-rw-r--r-- | src/mongo/util/str.cpp | 7 | ||||
-rw-r--r-- | src/mongo/util/str.h | 6 | ||||
-rw-r--r-- | src/mongo/util/str_test.cpp | 10 |
3 files changed, 23 insertions, 0 deletions
diff --git a/src/mongo/util/str.cpp b/src/mongo/util/str.cpp index 7209fd90e2e..0f04497f95f 100644 --- a/src/mongo/util/str.cpp +++ b/src/mongo/util/str.cpp @@ -236,4 +236,11 @@ boost::optional<size_t> parseUnsignedBase10Integer(StringData fieldName) { return boost::none; } +std::string convertDoubleToString(double d, int prec) { + char buffer[StringBuilder::MONGO_DBL_SIZE]; + int z = snprintf(buffer, sizeof(buffer), "%.*g", prec, d); + invariant(z >= 0); + return std::string(buffer); +} + } // namespace mongo::str diff --git a/src/mongo/util/str.h b/src/mongo/util/str.h index bddfff282b2..b2ee26dbbdb 100644 --- a/src/mongo/util/str.h +++ b/src/mongo/util/str.h @@ -344,4 +344,10 @@ std::string escape(StringData s, bool escape_slash = false); */ boost::optional<size_t> parseUnsignedBase10Integer(StringData integer); +/** + * Converts a double to a string with specified precision. If unspecified, default to 17, which is + * the maximum decimal precision possible from a standard double. + */ +std::string convertDoubleToString(double d, int prec = 17); + } // namespace mongo::str diff --git a/src/mongo/util/str_test.cpp b/src/mongo/util/str_test.cpp index 68d06b7535c..66ee0f77196 100644 --- a/src/mongo/util/str_test.cpp +++ b/src/mongo/util/str_test.cpp @@ -270,4 +270,14 @@ TEST(StringUtilsTest, WhitespaceWithinNumberFailsToParse) { boost::optional<size_t> result = parseUnsignedBase10Integer(" 10"); ASSERT(!result); } + +TEST(StringUtilsTest, ConvertDoubleToStringWithProperPrecision) { + ASSERT_EQUALS(std::string("1.9876543219876543"), convertDoubleToString(1.98765432198765432)); + ASSERT_EQUALS(std::string("1.987654321"), convertDoubleToString(1.987654321, 10)); + ASSERT_EQUALS(std::string("1.988"), convertDoubleToString(1.987654321, 4)); + ASSERT_EQUALS(std::string("6e-07"), convertDoubleToString(6E-7, 10)); + ASSERT_EQUALS(std::string("6e-07"), convertDoubleToString(6E-7, 6)); + ASSERT_EQUALS(std::string("0.1000000006"), convertDoubleToString(0.1 + 6E-10, 10)); + ASSERT_EQUALS(std::string("0.1"), convertDoubleToString(0.1 + 6E-8, 6)); +} } // namespace mongo::str |