I would like to understand from when format specifier %g
for double starts printing values in exponential format.
myTest.c
#include <stdio.h>
int main() {
double val = 384615.38462;
double val2 = 9999999;
printf ("val = %g\n",val);
printf ("val2 = %g\n",val2);
return 0;
}
Compiled using gcc :
gcc version 4.5.2 (GCC)
Target: i386-pc-solaris2.11
Output :
val = 384615
val2 = 1e+07
Question:
Why val
is printed as integer and why val2
has been converted to exponential format even when I have not used %lf
in printf
.
Is there a range from when it will start print values using exponential format? If yes, Is there any way we can guess what could be the value range ?
Thanks in Advance.
According to the man 3 printf
:
g, G
The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.
And the C11 – ISO/IEC 9899:2011 standard draft N1570 (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf):
g,G
A double argument representing a floating-point number is converted in style f or e (or in style F or E in the case of a G conversion specifier), depending on the value converted and the precision. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:
— if P > X ≥ −4, the conversion is with style f (or F) and precision P − (X + 1).
— otherwise, the conversion is with style e (or E) and precision P − 1.
Finally, unless the # flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point character is removed if there is no fractional portion remaining. A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier.
The man says
g, G
The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With