From bbf4dac6a3f88a8ff26f2851f183a7cef3e709c4 Mon Sep 17 00:00:00 2001 From: Wouter van Oortmerssen Date: Mon, 22 Jan 2018 10:11:51 -0800 Subject: [PATCH] Made doubles output with higher precision in JSON and elsewhere. Change-Id: I5dd8f3a7c315c40b86a67aba5c2cca4d36363523 Tested: on Linux. --- include/flatbuffers/util.h | 13 ++++++++++--- tests/monsterdata_test.golden | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/include/flatbuffers/util.h b/include/flatbuffers/util.h index a9ac01c76..27a965325 100644 --- a/include/flatbuffers/util.h +++ b/include/flatbuffers/util.h @@ -76,12 +76,15 @@ inline std::string NumToString(unsigned long long t) { #endif // defined(FLATBUFFERS_CPP98_STL) // Special versions for floats/doubles. -template<> inline std::string NumToString(double t) { +template std::string FloatToString(T t, int precision) { // to_string() prints different numbers of digits for floats depending on // platform and isn't available on Android, so we use stringstream std::stringstream ss; // Use std::fixed to surpress scientific notation. - ss << std::fixed << t; + ss << std::fixed; + // Default precision is 6, we want that to be higher for doubles. + ss << std::setprecision(precision); + ss << t; auto s = ss.str(); // Sadly, std::fixed turns "1" into "1.00000", so here we undo that. auto p = s.find_last_not_of('0'); @@ -91,8 +94,12 @@ template<> inline std::string NumToString(double t) { } return s; } + +template<> inline std::string NumToString(double t) { + return FloatToString(t, 12); +} template<> inline std::string NumToString(float t) { - return NumToString(static_cast(t)); + return FloatToString(t, 6); } // Convert an integer value to a hexadecimal string. diff --git a/tests/monsterdata_test.golden b/tests/monsterdata_test.golden index fe55a8753..6def28f76 100644 --- a/tests/monsterdata_test.golden +++ b/tests/monsterdata_test.golden @@ -3,7 +3,7 @@ x: 1.0, y: 2.0, z: 3.0, - test1: 3.0, + test1: 3.14159265359, test2: "Green", test3: { a: 10,