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 fo
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.
With boost::to_string
you cannot control the format either but it will output something closer to what you see in the screen. Same with std::lexical_cast<std::string>
.
For a function-like operation with format control, use str(boost::format("...format...")% 0.33)
.
What's the difference between std::to_string, boost::to_string, and boost::lexical_cast<std::string>?
A varied solution to the problem since to_string
doesn't work.
"The Magic Formula" - my CS2400 teacher
std::cout.setf(ios::fixed);
std::cout.setf(ios::showpoint);
std::cout.precision(2);
const double x = 0.33, y = 42.3748;
std::cout << "$" << x << std::endl;
std::cout << "$" << y << std::endl;
Outputs:
$0.33
$42.37
any following output you do with decimal numbers will be set as so.
you can always change the setf and precision as you see fit.
To leave out the trailing zeros:
std::ostringstream oss;
oss << std::setprecision(8) << std::noshowpoint << double;
std::string str = oss.str();
Hope that helps.
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 );
double val
std::wstringstream wss;
wss << val;
cout << wss.str().c_str();