91

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?

Marco Bonelli
  • 55,971
  • 20
  • 106
  • 115
learnvst
  • 14,665
  • 13
  • 72
  • 113

1 Answers1

133

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();
}
user276648
  • 5,669
  • 6
  • 58
  • 82
hmjd
  • 117,013
  • 19
  • 199
  • 247
  • 19
    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. – 3Dave Feb 01 '14 at 00:09
  • 2
    isn'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
  • 8
    To 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
  • 3
    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. :-) – Joe May 09 '16 at 21:58
  • 3
    You 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