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

C++StringC++11DoubleFloating

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlearnvstView Question on Stackoverflow
Solution 1 - C++hmjdView Answer on Stackoverflow