Something like this should work:
double round_to_n_digits(double x, int n) { double scale = pow(10.0, ceil(log10(fabs(x))) + n); return round(x * scale) / scale; }
Alternatively, you can simply use sprintf / atof to convert to string and vice versa:
double round_to_n_digits(double x, int n) { char buff[32]; sprintf(buff, "%.*g", n, x); return atof(buff); }
Test code for both of the above functions: http://ideone.com/oMzQZZ
Please note that in some cases incorrect rounding may occur, for example. as pointed out by
@clearScreen in the comments below, 13127.15 is rounded to 13127.1 instead of 13127.2.
source share