Tuesday, 15 September 2015

c - Floating point to string representation -



c - Floating point to string representation -

consider next code snippet:

char str[1000]; float b ; b= 0.0615; sprintf( &(str[0]), "%1.0e", b);

after execution of lastly statement, expected str contain 6.15e-2. however, getting value 5e-315.

where going wrong. how expected value?

you cannot 2 digits precision format string, specified 1 digit after comma (that .0 part after 1).

what works me is

#include <stdio.h> #include <string.h> main() { char str[1000]; float b ; b= 0.0615; sprintf( &(str[0]), "%.2e", b); puts(str); }

prints 6.15e-02

the almighty c/c++ documentation says:

.number:

for a, a, e, e, f , f specifiers: number of digits printed after decimal point (by default, 6).

c floating-point string-formatting

No comments:

Post a Comment