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?
sprintf stands for “String print”. Instead of printing on console, it store output on char buffer which are specified in sprintf.
The simplest format specification contains only the percent sign and a type character (for example, %s). The percent sign: If a percent sign (%) is followed by a character that has no meaning as a format field, the character is simply copied to the buffer. For example, to print a percent sign character, use %%.
The printf precision specifiers set the maximum number of characters (or minimum number of integer digits) to print. A printf precision specification always begins with a period (.) to separate it from any preceding width specifier.
According to most sources I've found, across multiple languages that use printf specifiers, the %g specifier is supposed to be equivalent to either %f or %e - whichever would produce shorter output for the provided value.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With