C/C++ specifies at least two exponent digits with printf("%e",...)
. To print only 1, and to deal with Visual Studio which, by default, prints at least 3, additional code is needed.
Consider IOStreams @Dietmar Kühl
If C++ code still wants to use printf()
style formats:
Adjusting the value of a double
before calling printf()
too often results in rounding issues, range shorting and general corner case failures like dealing with log10(0.0)
. Also consider large double
just near a power-of-10 where log10()
may come up short, -0.0
, INF
, NAN
.
In this case, better to post-process the string.
double var = 1.23e-9;
// - 1 . x e - EEEEE \0
#define ExpectedSize (1+1+1+1+1+1+ 5 + 1)
char buf[ExpectedSize + 10];
snprintf(buf, sizeof buf, "%.1e", var);
char *e = strchr(buf, 'e'); // lucky 'e' not in "Infinity" nor "NaN"
if (e) {
e++;
int expo = atoi(e);
snprintf(e, sizeof buf - (e - buf), "%1d", expo);
}
printf("'%6s'\n", buf); // '1.2e-9'
Note: %e
is amiable to post-processing as its width is not so unwieldy as "%f"
. sprintf(buf, "%f", DBL_MAX)
could be 1000s of char
.