Maanu
Maanu

Reputation: 5203

Issue with %g precision

When I used printf("%.6g\n",36.666666662);, i expected the output 36.666667. But the actual output is 36.6667

What is wrong with the format I have given? My aim is to have 6 decimal digits

Upvotes: 6

Views: 1859

Answers (1)

Mark Byers
Mark Byers

Reputation: 838376

This is correct behaviour. According to cplusplus.com:

For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point.

For g and G specifiers: This is the maximum number of significant digits to be printed.

If you use f instead of g then it will work as you expected.


Example code

#include <stdio.h>

int main(void) {
    printf("%.6g\n", 36.666666662);
    printf("%.6f\n", 36.666666662);
    return 0;
}

Result

36.6667
36.666667

See it working online: ideone.

Upvotes: 11

Related Questions