4

Possible Duplicate:
Rounding Number to 2 Decimal Places in C

I 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?

Community
  • 1
  • 1
testCoder
  • 7,155
  • 13
  • 56
  • 75
  • @melpomene, thanks i have found http://stackoverflow.com/questions/994764/rounding-doubles-5-sprintf but i need to get return value not only print it – testCoder Dec 22 '12 at 14:08
  • Decimal point is relevant for display. One could round to the nearest negative power of ten - but - why would you want such a thing? – Pavel Radzivilovsky Dec 22 '12 at 14:11
  • 2
    **Voting to re-open**. The cited "duplicate" is a special case, requiring rounding to only 2 decimal places. This question asks the more general case of rounding to an arbitrary number of decimal places. – andand Dec 23 '12 at 02:35

4 Answers4

4

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];
}
andand
  • 17,134
  • 11
  • 53
  • 79
1

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.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

here's a (very) simple function,

double round1(double num, int N) {
      int temp=(int) num*pow(10,N); 
      double roundedN= temp/pow(10,N);
      return roundedN;
}
Muhammad
  • 89
  • 1
  • 5
0

In C standard, such function does not exist. Anyway, you can write your own.

#include <math.h>

/* Round `n` with `c` digits after decimal point. */

double nround (double n, unsigned int c)
{
    double marge = pow (10, c);
    double up    = n * marge;
    double ret   = round (up) / marge;

    return ret;
}

See also the comments above about floating points "decimal point".

md5
  • 23,373
  • 3
  • 44
  • 93