title: Decimal precision vs. number of digits in printf(), fprintf() in format %g vs. %f
body: <p>After surfing for a while I could not find a clear explanation for this issue. Maybe anyone could clarify me why it works so.</p>
  
  <p>In some code I am saving some <code>double</code> numbers to file by <code>fprintf</code> (after properly initializing the file stream). Because, a priori, I don't know what number is passed to my program, and in particular, what its format is, e.g. <code>0.00011</code> vs. <code>1.1e-4</code>, I thought to use the format specifier <code>%.5g</code> instead of <code>%.5f</code>, where, I want to save my data with a 5-digit decimal precision.</p>
  
  <p>However, it turns out that in <code>%g</code> the decimal precision of my saved numbers is correct if the numbers have a integer part equal to <code>0</code>, otherwise is not, like for example:</p>
  
  <pre><code>FILE *fp;
  fp = fopen("mydata.dat","w+"); //Neglecting error check for brevity
  double value[2] = {0.00011,1.00011};
  printf("\ng-format\n");
  for(int i=0;i&lt;2;i++){ 
      frintf(fp,"%.5g\n",value[i]);
      printf("%.5g\n",value[i]);
  }
  printf("\n\nf-format\n");
  for(int i=0;i&lt;2;i++){
      frintf(fp,"%.5f\n",value[i]);
      printf"%.5f\n",value[i]);
  } 
  fclose(fp);
  </code></pre>
  
  <p>This produces the following output to file (and on the std stream):</p>
  
  <pre><code>g-format
  0.00011
  1.0001
  
  f-format
  0.00011
  1.00011 
  </code></pre>
  
  <p>So, why the choice of <code>%g</code> is 'eating' decimal digits as soon as the integer part is not zero? </p>