views:

553

answers:

5

I am trying to populate a string with the double value using a sprintf like this sprintf(S, "%f", val); But the precision is being cut of to 6 decimal places. I need about 10 decimal places for the precision.

Kindly tell me how that can be achieved.

+5  A: 

What you want is a modifier:

sprintf(S, "%.10f", val);

man sprintf will have many more details on format specifiers.

Yann Ramin
Just a note: if he's using a double, would using "lf" be more correct?
Jeremy Banks
No, %f is correct for double.
ChrisN
floats only carry about 6 digits of precision. use %lf for a double.
EvilTeach
+6  A: 

%[width].[precision]

Width should include the decimal point.

%8.2 means 8 characters wide; 5 digits before the point and 2 after. One character is reserved for the point.

5 + 1 + 2 = 8

Vulcan Eager
A: 

For a more complete reference, see the Wikipedia printf article, section "printf format placeholders" and a good example on the same page.

Jegschemesch
+1  A: 

Take care - the output of sprintf will vary via C locale. This may or may not be what you want. See LC_NUMERIC in the locale docs/man pages.

dajobe
+1  A: 

%f is for float values

try using %lf instead. It is designed for doubles (which used to be called long floats)

double x = 3.14159265;
printf("15.10lf\n", x);

EvilTeach