tags:

views:

236

answers:

3
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 6 decimal precision. I would like to get an output "s0.0000005". Could you please advice me on how to achieve this? Thanks

+1  A: 

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.

Mark E
%lf is for long double. %9.7f should be used for a double.
progrmr
@kk6yb: `%lf` is undefined for C89, and the same as `%f` for C99 (where both are good to print `double` values). For a long double, the correct conversion specifier is `%Lf`.
pmg
More precisely, in `'%X.Yf'` the `Y` represents the number of places after the decimal to display (the default is 6) and the `X` represents the minimum number of characters to display. In your case the `X` is not necessary, but you will need to add the `.Y` where `Y` is the number of decimal places to print.
bta
@pmg: you are correct, %Lf is for long doubles. It's different from the literal constants, where 0.0l and 0.0L both specify a long double literal.
progrmr
A: 

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

progrmr
`%lf` is undefined for C89, and the same as `%f` for C99. For a long double, the correct conversion specifier is `%Lf`.
pmg
That will print 6 decimal places - so it will most likely print 0.000000 rather than 0.000001. Using "%9.7f" is correct for 7 decimal places.
Jonathan Leffler
Hmmm, yes, I didn't pay attention to the decimal places. Point is that `%lf` expects a `double` in C99; `%Lf` expects a `long double`.
pmg
@pmg: since a double is passed (and would be even if 'a' was float), there isn't a problem with using "%9.7lf" that I can see.
Jonathan Leffler
+2  A: 

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 A digits before decimal point & B digits after decimal point :)

nthrgeek