C++11 std::to_string(double) - No trailing zeros
Today I tried out some new functions of the C++11 STL and encountered std::to_string
.
Lovely, lovely set of functions. Creating a stringstream object for just one double-to-string conversion always seemed overkill to me, so I'm glad we can now do something like this:
std::cout << std::to_string(0.33) << std::endl;
The result?
0.330000
I'm not entirely content with that. Is there a way to tell std::to_string
to leave out the trailing zeros? I searched the internet, but as far as I can see the function takes only one argument (the value to be converted). Back in 'the old days' with stringstreams, you could set the width of the stream, but I'd rather not convert back.
Anyone encountered this problem before/has a solution? Some StackOverflow searches yielded nothing.
(A C++11 STL reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string)
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
.
To leave out the trailing zeros:
std::ostringstream oss;
oss << std::setprecision(8) << std::noshowpoint << double_value;
std::string str = oss.str();
Note: #include <sstream>
and #include <iomanip>
std::to_string(double)
is defined by the standard to just return the same sequence of characters that would be generated by sprintf(buf, "%f", value)
. No more, no less, especially no way to tweak the format specifier. So no, there is nothing you can do.