Why does printf("%.6g, <value>) ignore zeroes after decimal point?

c, double, floating-point, precision, printf

Solution

Is the `"%f"` format specifier:

printf("%.6f\n",0.007943989)  // prints 0.007944

what you're looking for? Keep in mind that this won't automatically switch over to the `%e` format style if the number warrants it, so this might not be exactly what you're looking for either.

For example, the following:

printf("%.6g\n",0.00007943989);
printf("%.6f\n",0.00007943989);

prints:

7.94399e-005
0.000079

and it's not clear if you want the exponential form for the smaller numbers that `"%g"` provides.

Note that the spec for `%f` and `%g` has a slightly different behavior for how the precision specification is handled.

- for `%f`: "the number of digits after the decimal-point character is equal to the precision specification"

- for `%g`: "with the precision specifying the number of significant digits"

And that the run of zeros after the decimal point do not count toward significant digits (which exlpains the behavior you see for `%g`).

Problem

I want to print maximum of 6 digits after the decimal point, so I used the following: ``` printf("%.6g",0.127943989); ``` the output of `printf` is 0.127944 which is correct, but when I tried this: ``` printf("%.6g",0.007943989); ``` the output became 0.00794399 which is not what I expected to see! It seems that `printf` ignores zeros after the decimal point. So how can I force it to output maximum of 6 digit precision?

Original source