user164054
user164054

Reputation: 205

'sprintf': double precision in C

Consider:

double a = 0.0000005l;
char aa[50];
sprintf(aa, "%lf", a);
printf("%s", aa);

Output: s0.000000

In the above code snippet, the variable aa can contain only six decimal precision. I would like to get an output like "s0.0000005". How do I achieve this?

Upvotes: 19

Views: 133899

Answers (3)

whacko__Cracko
whacko__Cracko

Reputation: 6692

From your question it seems like you are using C99, as you have used %lf for double.

To achieve the desired output replace:

sprintf(aa, "%lf", a);

with

sprintf(aa, "%0.7f", a);

The general syntax "%A.B" means to use B digits after decimal point. The meaning of the A is more complicated, but can be read about here.

Upvotes: 38

progrmr
progrmr

Reputation: 77191

The problem is with sprintf

sprintf(aa,"%lf",a);

%lf says to interpet "a" as a "long double" (16 bytes) but it is actually a "double" (8 bytes). Use this instead:

sprintf(aa, "%f", a);

More details here on cplusplus.com

Upvotes: -2

Mark Elliot
Mark Elliot

Reputation: 77044

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

Upvotes: 7

Related Questions