Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'sprintf': double precision in C

Tags:

c

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?

like image 654
user164054 Avatar asked Nov 23 '09 22:11

user164054


People also ask

What is sprintf () in C?

sprintf stands for “String print”. Instead of printing on console, it store output on char buffer which are specified in sprintf.

What does %s mean 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 %%.

How do I specify precision in printf?

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.

What is %g in printf?

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.


2 Answers

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.

like image 82
whacko__Cracko Avatar answered Sep 22 '22 18:09

whacko__Cracko


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.

like image 27
Mark Elliot Avatar answered Sep 21 '22 18:09

Mark Elliot