Round in C with N digits after decimal point
Solution 1
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];
}
Solution 2
Whilst "answerd" gives a decent answer, here's one that works for arbitrarily large numbers:
double round1(double num, int N) {
ASSERT(N > 0);
double p10 = pow(10,N);
return round(num* p10) / p10;
}
Of course, as stated, floating point numbers don't have a set number of decimal digits, and this is NOT guaranteed to PRINT as 3.70000 if you call printf("%8.5f", round1(3.7519, 1));
for example.
testCoder
Updated on December 23, 2020Comments
-
testCoder over 3 years
Possible Duplicate:
Rounding Number to 2 Decimal Places in CI have not found a function with a signature
double round(double d, int digits)
like here in c. When i try to build i get a error:error: too many arguments to function 'round'
How can I round in C with N digits after the decimal point?