Sriraman
Sriraman

Reputation: 51

How %g works in printf

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

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

Use the shortest representation: %e or %f is not precise enough.

C11 7.21.6.1 The fprintf function

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.

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

Related Questions