102

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
  • 63,369
  • 21
  • 118
  • 128
learnvst
  • 15,455
  • 16
  • 74
  • 121

1 Answers1

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();
}
Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • 22
    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
  • 4
    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
  • 10
    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
  • 5
    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
  • 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