How to use "%f" to populate a double value into a string with the right precision
Solution 1
%[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
Solution 2
What you want is a modifier:
sprintf(S, "%.10f", val);
man sprintf will have many more details on format specifiers.
Solution 3
For a more complete reference, see the Wikipedia printf article, section "printf format placeholders" and a good example on the same page.
Solution 4
%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);
Solution 5
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.
Comments
-
user1121201 almost 2 years
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?