Set precision of std::to_string when converting fl

2019-01-07 12:49发布

This question already has an answer here:

In C++11, std::to_string defaults to 6 decimal places when given an input value of type float or double. What is the recommended, or most elegant, method for changing this precision?

1条回答
2楼-- · 2019-01-07 13:18

There is no way to change the precision via to_string() but the setprecision IO manipulator could be used instead:

#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();
}
查看更多
登录 后发表回答