How to set decimal precision in C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

float set_precision(float f, float precision) { 
    return floor(pow(10, precision) * f) / pow(10, precision); 
}


int main()
{
	float f = 376.87639512f;
	
	printf("%.1f\n", set_precision(f, 1)); 
	printf("%.2f\n", set_precision(f, 2)); 
	printf("%.3f\n", set_precision(f, 3)); 
	printf("%.4f\n", set_precision(f, 4)); 
	
	return 0;
}


        
/*
run:
        
376.8
376.87
376.876
376.8764
      
*/

 



answered Sep 5, 2019 by avibootz

Related questions

1 answer 160 views
1 answer 175 views
1 answer 103 views
1 answer 95 views
1 answer 143 views
1 answer 171 views
...