2

As per documentation, "g - shorter of %e and %f"

I have executed this statement:

printf("e:%1\$.3e\nf:%1\$.3f\ng:%1\$.3g", .123e2);

And this is output:

e:1.230e+1 // long value
f:12.300 // shorter value
g:12.3 // here g gives something else

Why "g" gives something else, am I getting the docs wrong?

$ php -v
PHP 7.1.10 (cli) (built: Oct 19 2017 15:16:13) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
    with Xdebug v2.5.1, Copyright (c) 2002-2017, by Derick Rethans
Dmitriy Lezhnev
  • 801
  • 2
  • 10
  • 18
  • This issue isn't unique to PHP, although PHP is the only language I know where the *official documentation* makes this error. The same misdocumentation of the `g` specifier can be found in relation to many languages, including C - and the real behaviour is the same in all of them. See my writeup at [What precisely does the %g printf specifier mean?](https://stackoverflow.com/questions/54162152/what-precisely-does-the-g-printf-specifier-mean), which quotes the same PHP docs that you quote here, and in which I explain how the real behaviour differs from just picking the shorter of `%f` and `%e`. – Mark Amery Jan 12 '19 at 18:48

1 Answers1

0

sprintf() eventually delegates to the sprintf(3) C function. From the printf(3) man page:

Precision

   [...] This gives ... the maximum number of significant digits for g and G 
   conversions...

Therefore the PHP documentation is, at best, inaccurate.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358