title: C compatible printf output for Java
body: <p>I'd want to convert float/double to string, in Java and C, such that the outputs are both <strong>consistent</strong> and <strong>user friendly</strong>.</p>
  
  <p>By "user friendly", I mean the string should be human readable and sound: a maximum number of significant digits, and some automatic switching to scientific notation when appropiate (the double could span all the valid range).</p>
  
  <p>By "consistent" I mean that the strings should be <strong>exactly</strong> the same in Java and C (I'd tolerate some exceptions if they are really rare). </p>
  
  <p>Why not use simply some <code>printf</code> format string, as <code>"%.5g"</code>? That works... almost. But sadly the meaning of the precision field is quite <a href="https://stackoverflow.com/a/13730799/277304">different</a> in Java and C. Also, the switching from-to scientific notation is not very consistent, nor even the format itself (2 or 3 digits for the exponent...). And different C compilers sometimes produce different results.</p>
  
  <p>Examples of differences for <code>"%.5g"</code></p>
  
  <pre><code>double                  Java %.5g         gcc %.5g      tcc %.5g
  1234.0                  1234.0            1234          1234 
  123.45678               123.46            123.45678     123.46
  0.000123456             0.00012346        0.00012346    0.00012346
  0.000000000000123456    1.2346e-13        1.2346e-13    1.2346e-013
  </code></pre>
  
  <p>I can code a function in C or Java (or both), but I wonder if someone has already dealt with this. I'm not very concerned with performance, but yes with portability across C compilers.</p>