Jesteś pewny, że nie wystarczy Ci ustawienie precyzji podczas wyświetlania zmiennej?
Jeśli nie... http://ideone.com/VmRrgp
#include <stdio.h>
#include <math.h>
int pow_i(int base, int exp){
int result = 1;
while (exp){
if (exp & 1)
result *= base;
exp >>= 1;
base *= base;
}
return result;
}
float round_float_precision(float x, unsigned digits){
unsigned precision = pow_i(10, digits);
return roundf(x*precision)/precision;
}
int main(void) {
float x = 123.456;
printf("Two digits of precision\n");
printf("- by printf - %.2f\n", x);
printf("- by setting value precision - %f\n", round_float_precision(x, 2));
return 0;
}
out:
Two digits of precision
- by printf - 123.46
- by setting value precision - 123.460000
//EDIT: tyle się spóźnić...