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

Set precision of std::to_string when converting floating point values

本文关键字:to string 精度 std 设置 转换      更新时间:2023-10-16

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

无法通过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 std::move(out).str();
}