Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 std::to_string(double) - No trailing zeros

Tags:

c++

c++11

stl

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)

like image 787
Stijn Frishert Avatar asked Dec 03 '12 15:12

Stijn Frishert


4 Answers

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 );
str.erase ( str.find_last_not_of('.') + 1, std::string::npos );
like image 75
Marshall Clow Avatar answered Nov 14 '22 16:11

Marshall Clow


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.

like image 42
rubenvb Avatar answered Nov 14 '22 16:11

rubenvb


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.

like image 16
Mike Seymour Avatar answered Nov 14 '22 18:11

Mike Seymour


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>

like image 16
Ivan Folgueira Bande Avatar answered Nov 14 '22 17:11

Ivan Folgueira Bande