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
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
.
Create a custom convert function, remove the tailing zeros if necessary.
//! 2018.05.14 13:19:20 CST
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
//! Create a custom convert function, remove the tailing zeros if necessary.
template<typename T>
std::string tostring(const T &n) {
std::ostringstream oss;
oss << n;
string s = oss.str();
int dotpos = s.find_first_of('.');
if(dotpos!=std::string::npos){
int ipos = s.size()-1;
while(s[ipos]=='0' && ipos>dotpos){
--ipos;
}
s.erase ( ipos + 1, std::string::npos );
}
return s;
}
int main(){
std::cout<< tostring(1230)<<endl;
std::cout<< tostring(12.30)<<endl;
}
The input numbers :
1230
12.30
Compile with -std=c++11
, then the result:
1230
12.3
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.