Using recursion (which is going to be slow for some values of digits)
#include <math.h>
double my_round(double x, unsigned int digits) {
if (digits > 0) {
return my_round(x*10.0, digits-1)/10.0;
}
else {
return round(x);
}
}
A method likely to be somewhat faster, but which relies on a single call to the slow pow
function:
#include <math.h>
double my_round(double x, unsigned int digits) {
double fac = pow(10, digits);
return round(x*fac)/fac;
}
An even faster method is to precompute a lookup table with the likely powers and use that instead of pow
.
#include <math.h>
double fac[]; // population of this is left as an exercise for the reader
double my_round(double x, unsigned int digits) {
return round(x*fac[digits])/fac[digits];
}