Question

I am trying to populate a string with a double value using a sprintf like this:

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

But the precision is being cut off to six decimal places. I need about 10 decimal places for the precision.

How can that be achieved?

Was it helpful?

Solution

%[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

OTHER TIPS

What you want is a modifier:

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

man sprintf will have many more details on format specifiers.

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.

%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);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top