I suggest you call snprintf
with format specifier "%.16g"
- that prints a double
in decimal with 16 significant digits of precision. See Number of Digits Required For Round-Trip Conversions for more details. E.g.:
inline std::string as_string(double value) {
char buf[32];
return std::string(buf, std::snprintf(buf, sizeof buf, "%.16g", value));
}
*printf
functions are fundamental conversion routines, everything else uses these.
std::to_string
in GNU C++ standard library does:
inline string to_string(double __val) {
const int __n = __gnu_cxx::__numeric_traits<double>::__max_exponent10 + 20;
return __gnu_cxx::__to_xstring<string>(&std::vsnprintf, __n, "%f", __val);
}
std::ostream
also calls *snprintf
under the hood to format numbers.
Also note that 3.14159267
is double
. A float
constant requires f
suffix, e.g. 3.14159267f
.