 <p>Use <code>snprintf()</code> to find out how many characters you need:</p> <pre><code>#include &lt;float.h&gt; /* DBL_DIG */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(void) { double x = rand() / (double)RAND_MAX; char find_len[1]; int need_len; char *buf; need_len = snprintf(find_len, 1, "%.*g", DBL_DIG, x); buf = malloc(need_len + 1); if (buf) { int used = sprintf(buf, "%.*g", DBL_DIG, x); printf("need: %d; buf:[%s]; used:%d\n", need_len, buf, used); free(buf); } return 0; } </code></pre> <p><s>You need a C99 compiler for <code>snprintf()</code>.</s><br> <code>snprintf()</code> was defined by the C99 standard. A C89 implementation is not required to have <code>snprintf()</code> defined, and if it has as an extension, it is not required to "work" as described by the C99 Standard.</p>