在C ++ 11中,当给定类型为float
或double
的输入值时,std :: to_string默认为小数点后6位。改变这种精度的推荐方法或最优雅的方法是什么?
答案 0 :(得分:87)
无法通过to_string()
更改精度,但可以使用setprecision
IO操纵器:
#include <sstream>
template <typename T>
std::string to_string_with_precision(const T a_value, const int n = 6)
{
std::ostringstream out;
out.precision(n);
out << std::fixed << a_value;
return out.str();
}