Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Precision in C programming

September 28, 2013 Posted by: GPA Views: 25925 0 comments

Problem

How to format string in C programming.

Solution

Sometimes we need to round off double two decimal points or display 3 decimal points even if they're both 0. For example if output of program is 1565, it needs to be 1565.00. How do you do it? For this you can use precision numbers.

For integer numbers example (%5d) precision 5 specifier shows the minimum number of digits to be printed. More detail information about all precision specifieres You can read in example below. 

Example:



#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("globalproganswer.com\n\n");
printf(
"Right justifying integers in a field.\n");
printf("%6d\n", 1 );
printf("%6d\n", 12 );
printf("%6d\n", 123 );
printf("%6d\n", 1234 );
printf("%6d\n", 12345 );
printf("%6d\n\n", 123456 );

printf("\nUsing precision for integer number 455\n" );
printf("%%.2d = %.2d \n", 455);
//If the value to be written is shorter
//than this number, the result is padded with leading zeros
printf("%%.9d = %.9d\n", 455);

printf(
"\nUsing precision for floating-point number 455.58989965\n" );
printf("%%.2f = %.2f \n", 455.58989965);//here we have used 2 number precision for rounding this number 455.58989965
printf("%%.9f = %.9f\n", 455.58989965); //here we have used 9 number precision and it padded zero to the number
char* str="Example string";
printf( "\nUsing precision for strings: %s \n",str);
printf("Result of %%.5s = %.5s\n\n",str);//using .5 number we show only 5 character of string

system("PAUSE");
return 0;
}

Output

Function Precision

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe