diff --git a/include/flatbuffers/util.h b/include/flatbuffers/util.h index ab47d63ca..7d247dd07 100644 --- a/include/flatbuffers/util.h +++ b/include/flatbuffers/util.h @@ -42,10 +42,8 @@ namespace flatbuffers { // Convert an integer or floating point value to a string. // In contrast to std::stringstream, "char" values are -// converted to a string of digits. +// converted to a string of digits, and we don't use scientific notation. template std::string NumToString(T t) { - // 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; ss << t; return ss.str(); @@ -58,6 +56,26 @@ template<> inline std::string NumToString(unsigned char t) { return NumToString(static_cast(t)); } +// Special versions for floats/doubles. +template<> inline std::string NumToString(double t) { + // 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; + 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'); + if (p != std::string::npos) { + s.resize(p + 1); // Strip trailing zeroes. + if (s.back() == '.') s.pop_back(); // Strip '.' if a whole number. + } + return s; +} +template<> inline std::string NumToString(float t) { + return NumToString(static_cast(t)); +} + // Convert an integer value to a hexadecimal string. // The returned string length is always xdigits long, prefixed by 0 digits. // For example, IntToStringHex(0x23, 8) returns the string "00000023".