90

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?

4

1 回答 1

131

无法通过以下方式更改精度,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();
}
于 2013-05-17T09:50:14.920 回答