Setting decimal precision in C
Last Updated :
02 Jun, 2017
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:
#include<stdio.h>
#include<math.h>
int main()
{
float num = 5.48958123;
num = floor (10000*num)/10000;
printf ( "%f" , num);
return 0;
}
|
Output:
5.489500
We can generalize above method using pow()
float newPrecision( float n, float i)
{
return floor ( pow (10,i)*n)/ pow (10,i);
}
|
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.
#include<stdio.h>
int main()
{
float num = 5.48958123;
printf ( "%0.4f" , num);
return 0;
}
|
Output:
5.4896
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...