"A little progress everyday adds up to big results"

Monday, 12 January 2015

C Programming : Display only the significant digits after decimal point

Problem:
 
             In C++ programming, if we give the statements,

float pi = 3.1400f ;
cout<<pi ;

only 3.14 ( significant digits ) will be shown. 
          
             But, in C program , if we give
float pi = 3.1400f ;
printf ( "%f", pi ) ;

3.140000 will be displayed. 
            
The '%g' format specifier:      
       Of course we can use %0.2f. But, we may not always know how many decimal digits are there? In such situations we can make use of %g,


float pi = 3.1400f ;
printf ( "%g", pi ) ;

will print 3.14
 
Now, say 'Hi' to %g

No comments:

Post a Comment