title: How to 'cout' the correct number of decimal places of a double value?
body: <p>I need help on keeping the precision of a <code>double</code>. If I assign a literal to a double, the actual value was truncated.</p>
  
  <pre><code>int main() {
      double x = 7.40200133400;
      std::cout &lt;&lt; x &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>For the above code snippet, the output was <code>7.402</code><br>
  Is there a way to prevent this type of truncation? Or is there a way to calculate exactly how many floating points for a <code>double</code>? For example, <code>number_of_decimal(x)</code> would give 11, since the input is unknown at run-time so I can't use <code>setprecision()</code>.</p>
  
  <hr>
  
  <p>I think I should change my question to:
  How to convert a double to a string without truncating the floating points. i.e. </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;sstream&gt;
  
  template&lt;typename T&gt;
  std::string type_to_string( T data ) {
      std::ostringstream o;
      o &lt;&lt; data;
      return o.str();
  }
  
  int main() {
      double x = 7.40200;
      std::cout &lt;&lt; type_to_string( x ) &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>The expected output should be 7.40200 but the actual result was 7.402. So how can I work around this problem? Any idea?</p>