我想写我自己的lexical_cast
,它在将double
转换为std::string
时保留小数点。所以我使用ostringstream
并设置标志std::ios::showpoint
:stringstream:为什么“showpoint”的行为与“fixed”类似?
#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;
}
然而,这版画不必要0个数字,一个行为,我期望从设置std::ios::fixed
但不std::ios::showpoint
:
1.00000000000000
5.60000000000000
0.333333333333333
不设置std::ios::showpoint
它给
1
5.6
0.333333333333333
,但我想是这样的:
1.0
5.6
0.333333333333333
任何简单的方法?