Why printf with %.2g doesn't show two digits after the dot?

Viewed 168
#include <stdio.h>

int main()
{
    printf("%.2g %.2f\n", 2.925, 2.925);
}

I think that the right output should be:

2.93 2.93

Now, the output is the following:

2.9 2.92

There are two misunderstandings:

  1. Why '%.2g' doesn't show the two digits after dot?

  2. Why is the rounding off?

1 Answers

1. Why is there different number of digits?

Precision field in printf conversion specification is different for f and g conversions. From standard (C17 draft, 7.21.6 Formatted input/output functions):

  • An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversions, the number of digits to appear after the decimal-point character for a, A, e, E, f, and F conversions, the maximum number of significant digits for the g and G conversions, ...

So with f, precision only specifies number of digits after the decimal point, but with g it is the maximum number of all digits.

2. Why does the number round down?

When you use floating point number in source code, it needs to be converted from decimal form to binary form during compilation. Decimal number 2.925 cannot be converted to binary form exactly with the limited precision of your double type, and value is slightly less (2.92499999999999982236...). When rounded to 2 decimal digits, nearest value is 2.92.

Related