Set std :: to_string precision when converting floating point values

In C ++ 11, std :: to_string defaults to 6 decimal places if an input value of type float or double . What is the recommended or most elegant way to change this accuracy?

+46
c ++ string double c ++ 11 floating
May 17 '13 at 9:41
source share
1 answer

It is not possible to change the accuracy using to_string() , but instead, you can use the setprecision IO manipulator instead:

 #include <sstream> #include <iomanip> template <typename T> std::string to_string_with_precision(const T a_value, const int n = 6) { std::ostringstream out; out << std::setprecision(n) << a_value; return out.str(); } 
+61
May 17 '13 at 9:50
source share
— -



All Articles