The %g
specifier doesn't seem to behave in the way that most sources document it as behaving.
According to most sources I've found, across multiple languages that use printf
specifiers, the %g
specifier is supposed to be equivalent to either %f
or %e
- whichever would produce shorter output for the provided value. For instance, at the time of writing this question, cplusplus.com says that the g
specifier means:
Use the shortest representation: %e
or %f
And the PHP manual says it means:
g - shorter of %e and %f.
And here's a Stack Overflow answer that claims that
%g
uses the shortest representation.
And a Quora answer that claims that:
%g
prints the number in the shortest of these two representations
But this behaviour isn't what I see in reality. If I compile and run this program (as C or C++ - it's a valid program with the same behaviour in both):
#include <stdio.h>
int main(void) {
double x = 123456.0;
printf("%e
", x);
printf("%f
", x);
printf("%g
", x);
printf("
");
double y = 1234567.0;
printf("%e
", y);
printf("%f
", y);
printf("%g
", y);
return 0;
}
... then I see this output:
1.234560e+05
123456.000000
123456
1.234567e+06
1234567.000000
1.23457e+06
Clearly, the %g
output doesn't quite match either the %e
or %f
output for either x
or y
above. What's more, it doesn't look like %g
is minimising the output length either; y
could've been formatted more succinctly if, like x
, it had not been printed in scientific notation.
Are all of the sources I've quoted above lying to me?
I see identical or similar behaviour in other languages that support these format specifiers, perhaps because under the hood they call out to the printf
family of C functions. For instance, I see this output in Python:
>>> print('%g' % 123456.0)
123456
>>> print('%g' % 1234567.0)
1.23457e+06
In PHP:
php > printf('%g', 123456.0);
123456
php > printf('%g', 1234567.0);
1.23457e+6
In Ruby:
irb(main):024:0* printf("%g
", 123456.0)
123456
=> nil
irb(main):025:0> printf("%g
", 1234567.0)
1.23457e+06
=> nil
What's the logic that governs this output?
See Question&Answers more detail:
os