C++11 std::to_string(double) - No trailing zeros
If all you want to do is remove trailing zeros, well, that's easy.
std::string str = std::to_string (f);
str.erase ( str.find_last_not_of('0') + 1, std::string::npos );
The C++11 Standard explicitely says (21.5/7
):
Returns: Each function returns a string object holding the character representation of the value of its argument that would be generated by calling sprintf(buf, fmt, val) with a format specifier of "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", or "%Lf", respectively, where buf designates an internal character buffer of sufficient size
for the functions declared in this order:
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);
Thus, you cannot control the formatting of the resulting string.
std::to_string
gives you no control over the format; you get the same result as sprintf
with the appropriate format specifier for the type ("%f"
in this case).
If you need more flexibility, then you will need a more flexible formatter - such as std::stringstream
.