简体   繁体   中英

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

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?

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 ).

The ISO C standard requires that

An optional precision, in the form of a period ('.') followed by an optional decimal digit string... This gives ... the maximum number of significant digits for g and G conversions

Here is the output that you would get with GNU libc (GCC 4.5.1, libc 2.11; GCC 4.6.3, libc 2.15)

printf("%.6g\n", 0.12);
0.12
printf("%.6g\n", 0.1234567890);
0.123457
printf("%.6g\n", 0.001234567890);
0.00123457
printf("%#.6g\n", 0.001234567890);
0.00123457
printf("%.6g\n", 0.00001234567890);
1.23457e-05
printf("%#.6g\n", 0.00001234567890);
1.23457e-05

printf("%.6f\n", 0.12);
0.120000
printf("%.6f\n", 0.1234567890);
0.123457
printf("%.6f\n", 0.001234567890);
0.001235
printf("%#.6f\n", 0.001234567890);
0.001235
printf("%.6f\n", 0.001234567890);
0.000012
printf("%#.6f\n", 0.001234567890);
0.000012

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM