I'd like to write my own lexical_cast
which preserves the decimal point when converting double
to std::string
. So I'm using ostringstream
and set the flag std::ios::showpoint
:
#include <string>
#include <iostream>
#include <boost/lexical_cast.hpp>
template <typename Source>
std::string my_string_cast(Source arg){
std::ostringstream interpreter;
interpreter.precision(std::numeric_limits<Source>::digits10);
interpreter.setf(std::ios::showpoint);
interpreter << arg;
return interpreter.str();
}
int main(int argc, char** argv) {
std::cout << my_string_cast(1.0) << std::endl;
std::cout << my_string_cast(5.6) << std::endl;
std::cout << my_string_cast(1.0/3.0) << std::endl;
return 0;
}
This, however, prints unnecessary 0 digits, a behaviour I'd expect from setting std::ios::fixed
but not std::ios::showpoint
:
1.00000000000000
5.60000000000000
0.333333333333333
Without setting std::ios::showpoint
it gives
1
5.6
0.333333333333333
but I want something like this:
1.0
5.6
0.333333333333333
Any easy way?