-2

How do I round a non-floating point number? e.g. 9107609 down to 91 or to 911, etc.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Stuart Gordon
  • 185
  • 2
  • 10

4 Answers4

5

Divide by 100000 or 10000, respectively. C division rounds towards zero, so the numbers will always be rounded down. To round to the nearest integer, see this question.

Community
  • 1
  • 1
Adrian
  • 14,931
  • 9
  • 45
  • 70
1

Something like floor(number/(10^numberofdigitstocut)) or ceil(number/(10^numberofdigitstocut)) would do.

kos
  • 510
  • 3
  • 18
0
#include <math.h>

//returns n rounded to digits length
int round_int (int n, int digits)
{
   int d = floor (log10 (abs (n))) + 1; //number of digits in n

   return floor(n / pow(10, d-digits));
}
Bence Gedai
  • 1,461
  • 2
  • 13
  • 25
0

To round, use a half way addition (if positive, else subtract 10000/2)

int rounded = (9107609 + 10000/2)/10000;
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256