转换浮点值时设置std :: to_string的精度

时间:2013-05-17 09:41:59

标签: c++ string c++11 double floating

在C ++ 11中,当给定类型为floatdouble的输入值时,std :: to_string默认为小数点后6位。改变这种精度的推荐方法或最优雅的方法是什么?

1 个答案:

答案 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();
}