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?
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.
Floats have a static, fixed precision. You can't change it. What you can sometimes do, is round the number.
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.
To set fixed 2 digits after the decimal point use these first: cout. setf(ios::fixed); cout. setf(ios::showpoint); cout.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With