Setting decimal precision in C

How to print floating point numbers with a specified precision? Rounding is not required. For example, 5.48958123 should be printed as 5.4895 if given precision is 4.

For example, below program sets the precision for 4 digits after the decimal point:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to set precision in floating point numbers
#include<stdio.h>
#include<math.h>
int main()
{
   float num = 5.48958123;
  
   // 4 digits after the decimal point
   num = floor(10000*num)/10000;
  
   printf("%f", num);
   return 0;
}

chevron_right


Output:

5.489500

We can generalize above method using pow()

filter_none

edit
close

play_arrow

link
brightness_4
code

float newPrecision(float n, float i)
{
    return floor(pow(10,i)*n)/pow(10,i);
}

chevron_right



In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf(). Below is program to demonstrate the same
.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to set precision in floating point numbers
// using format specifier
#include<stdio.h>
  
int main() 
{
    float num = 5.48958123;
  
    // 4 digits after the decimal point  
    printf("%0.4f", num); 
    return 0;
}

chevron_right


Output:

5.4896

This article is contributed by Niharika Khandelwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.