title: C++ Precision: String to Double
body: <p>I am having a problem with precision of a double after performing some operations on a converted string to double.</p>
  
  <pre><code>#include &lt;iostream&gt;   
  #include &lt;sstream&gt;
  #include &lt;math.h&gt;
  
  using namespace std;
  
  // conversion function
  void convert(const char * a, const int i, double &amp;out)
  {
  
     double val;
  
     istringstream in(a);
     in &gt;&gt; val;
  
     cout &lt;&lt; "char a -- " &lt;&lt; a &lt;&lt; endl;
     cout &lt;&lt; "val ----- " &lt;&lt; val &lt;&lt; endl;
  
     val *= i;
  
     cout &lt;&lt; "modified val --- " &lt;&lt; val &lt;&lt; endl;
     cout &lt;&lt; "FMOD ----- " &lt;&lt; fmod(val, 1) &lt;&lt; endl;
  
     out = val;
  
     return 0;
  
  }
  </code></pre>
  
  <p>This isn't the case for all numbers entered as a string, so the error isn't constant.
  It only affects some numbers (34.38 seems to be constant).</p>
  
  <p>At the minute, it returns this when i pass in a = 34.38 and i=100:</p>
  
  <pre><code>char a -- 34.38
  Val ----- 34.38
  modified val --- 3438
  FMOD ----- 4.54747e-13
  </code></pre>
  
  <p>This will work if I change the Val to a float, as there is lower precision, but I need a double.</p>
  
  <p>This also is repro when i use atof, sscanf and strtod instead of sstream.</p>
  
  <p>In C++, what is the best way to correctly convert a string to a double, and actually return an accurate value?</p>
  
  <p>Thanks.</p>