How to 'cout' the correct number of decimal places of a double value?
<p>I need help to keep the precision of a double value. For example:</p>

<pre><code>int main() {
    double x = 7.40200133400;
    std::cout &lt;&lt; x &lt;&lt; "\n";
}
</code></pre>

<p>The output is <code>7.042</code>
Is there a way to prevent the truncation? Or is there a way to calculate exactly how many floating points of a double? For example: <code>number_of_decimal( x )</code> would gives 11, since the input is not known 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 truncated 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 one was 7.402. So how can I work around this problem?</p>
