Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with %g precision

Tags:

c++

c

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

like image 208
Maanu Avatar asked Dec 14 '12 12:12

Maanu


1 Answers

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.

like image 101
Mark Byers Avatar answered Nov 06 '22 06:11

Mark Byers