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?
Set precision of std::to_string when converting floating point values [duplicate]
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();
}
Nice, but it'd be great to be able to do this without creating a temp string. :/ Especially in a very, very tight inner loop. –
Among
isn't the inner string implicitly moved by being a returned rval? –
Execratory
I get "3e+01" for the 33.33~ case, even only using n = 1. –
Bagwig
To ensure the number of digits, also std::fixed must be passed. See sample in cplusplus.com/reference/iomanip/setprecision –
Bradbury
Using 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. :-) –
Thoer
You don't need
iomanip
for this: just use out.precision(n); out << a_value;
. Using iomanip
isn't even less typing. –
Kerby If you automatically want to choose the best available precision you can use
const unsigned int digits = std::numeric_limits<T>::digits10;
instead of the integer n –
Mindexpanding When I tried
float x = 107.2; cout<<to_string(x)
gives 107.199997. Is this normal? –
Leventhal 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? –
Carolyncarolyne
© 2022 - 2024 — McMap. All rights reserved.