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?
Asked
Active
Viewed 1e+01k times
1 Answers
152
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 std::move(out).str();
}
-
22Nice, but it'd be great to be able to do this without creating a temp string. :/ Especially in a very, very tight inner loop. – 3Dave Feb 01 '14 at 00:09
-
4isn't the inner string implicitly moved by being a returned rval? – Jules G.M. Aug 18 '14 at 22:40
-
I get "3e+01" for the 33.33~ case, even only using n = 1. – Jonny Oct 27 '15 at 10:03
-
10To ensure the number of digits, also std::fixed must be passed. See sample in http://www.cplusplus.com/reference/iomanip/setprecision/ – RED SOFT ADAIR Dec 02 '15 at 14:40
-
5Using string at all in a tight inner loop is a bad idea. Memory allocations are super slow. You are trying to use 1 memory allocation instead of having 2 memory allocations by avoiding a temporary. You try to avoid any memory allocations if you want performance by using sprintf and a stack allocated buffer. :-) – Joe May 09 '16 at 21:58
-
3You don't need `iomanip` for this: just use `out.precision(n); out << a_value;`. Using `iomanip` isn't even less typing. – Ruslan Dec 06 '17 at 07:29
-
If you automatically want to choose the best available precision you can use `const unsigned int digits = std::numeric_limits
::digits10;` instead of the integer n – Azrael3000 Nov 19 '19 at 09:47 -
When I tried `float x = 107.2; cout<
– Yunus Temurlenk Aug 16 '20 at 08:32 -
Could please someone confirm this: " isn't the inner string implicitly moved by being a returned rval? – Jules G.M. Aug 18, 2014 at 22:40 "? It's an interesting statement and I think it's correct? Could please someone confirm? – Vero May 16 '23 at 08:51