Reputation: 51
The %g
description says
Use the shortest representation:
%e
or%f
for example,
544666.678
is written as 544667
if %.6g
is used which is fine.
But the same number is written as 5.4467E+5
when %.5g
is used.
Why would it use exponential notation (%e
) here while 544670
(%f
) is shorter in length than that.
Can anyone please help me to understand? Is this a bug?
Similarly, 44.35
is written as 44.4
when %.1f
is used which is fine.
but 44.55
is written as 44.5
when %.1f
is used. Why isn't it written as 44.6
? Is this a bug?
Upvotes: 4
Views: 2841
Reputation: 122383
Use the shortest representation: %e or %f is not precise enough.
C11 7.21.6.1 The
fprintf
functionA
double
argument representing a floating-point number is converted in stylef
ore
(or in styleF
orE
in the case of aG
conversion specifier), depending on the value converted and the precision. LetP
equal the precision if nonzero,6
if the precision is omitted, or1
if the precision is zero. Then, if a conversion with style E would have an exponent ofX
:— if
P > X ≥ −4
, the conversion is with stylef
(orF
) and precisionP − (X + 1)
.— otherwise, the conversion is with style
e
(orE
) and precisionP − 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.
So in the example of %.5g
with 544666.678
, P
is 5
, and X
being 5
, according to the rule, the style e
is used because P > X ≥ −4
is false.
Upvotes: 5