Microsoft KB Archive/43392

= INFO: Clarification of the &quot;g&quot; Format Specifier for printf =

Article ID: 43392

Article Last Modified on 12/8/2003

-

APPLIES TO

 The C Run-Time (CRT), when used with:  Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 1.5 Professional Edition

 Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 2.0 Professional Edition</li></ul>

 Microsoft Visual C++ 4.0 Standard Edition</li></ul>

 Microsoft Visual C++ 5.0 Standard Edition</li></ul>

 Microsoft Visual C++ 6.0 Service Pack 5</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q43392

<div class="notice_section">

<div class="summary_section">

SUMMARY
In Microsoft C, the output format resulting from the printf format specifier &quot;g&quot; does not exactly match the output format resulting from either format specifier &quot;e&quot; or &quot;f&quot;. The documentation states that &quot;g&quot; will use either the &quot;f&quot; or &quot;e&quot; format, whichever is more compact. This is true in the sense of the overall format but there are some differences.

The precision value is interpreted differently in &quot;g&quot; format than in &quot;f&quot; format. The documentation explains this difference. The precision for &quot;f&quot; specifies the number of digits after the decimal point. The precision for &quot;g&quot; specifies the maximum number of significant digits printed. The following example demonstrates the difference described in the SUMMARY:

Sample Code

 * 1) include <stdio.h>

void main (void) {  double x = 2.0/3.0; /* 0.666... */   double y;

y = 6.0 + x; printf (&quot;%.4g\n&quot;, y); printf (&quot;%.4f\n&quot;, y); printf (&quot;%.4e\n\n&quot;, y);

y = 66.0 + x; printf (&quot;%.4g\n&quot;, y); printf (&quot;%.4f\n&quot;, y); printf (&quot;%.4e\n\n&quot;, y);

y = 666.0 + x; printf (&quot;%.4g\n&quot;, y); printf (&quot;%.4f\n&quot;, y); printf (&quot;%.4e\n\n&quot;, y);

y = 6666.0 + x; printf (&quot;%.4g\n&quot;, y); printf (&quot;%.4f\n&quot;, y); printf (&quot;%.4e\n\n&quot;, y);

y = 66666.0 + x; printf (&quot;%.4g\n&quot;, y);    /* switches to &quot;e&quot; notation here */ printf (&quot;%.4f\n&quot;, y); printf (&quot;%.4e\n\n&quot;, y); } The results of the above program are correct as shown below: <pre class="fixed_text">6.667 6.6667 6.6667e+000

66.67 66.6667 6.6667e+001

666.7 666.6667 6.6667e+002

6667 6666.6667 6.6667e+003

6.667e+004 66666.6667 6.6667e+004

Keywords: kbinfo kbcrt kbcode KB43392

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.