Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set precision of std::to_string when converting floating point values [duplicate]

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?

like image 918
learnvst Avatar asked May 17 '13 09:05

learnvst


People also ask

How do you set the precision of a float variable in C++?

You can't set precision of a float or double variable. Only for the input/output of such a variable. But you shouldn't be using float or double for monetary values to begin with, due to the fact that floating-point values/math is inprecise.

How do you change the precision of a float?

Floats have a static, fixed precision. You can't change it. What you can sometimes do, is round the number.

How do you set a precision to a double in C++?

You can set the precision directly on std::cout and use the std::fixed format specifier. double d = 3.14159265358979; cout. precision(17); cout << "Pi: " << fixed << d << endl; You can #include <limits> to get the maximum precision of a float or double.

How do I fix decimal places in C++?

To set fixed 2 digits after the decimal point use these first: cout. setf(ios::fixed); cout. setf(ios::showpoint); cout.


1 Answers

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();
}
like image 127
hmjd Avatar answered Oct 20 '22 01:10

hmjd