-2

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

Maroun
  • 91,013
  • 29
  • 181
  • 233
Stuart Gordon
  • 187
  • 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,346
  • 8
  • 42
  • 69
1

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

kos
  • 476
  • 3
  • 17
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,341
  • 1
  • 12
  • 24
0

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

int rounded = (9107609 + 10000/2)/10000;
chux - Reinstate Monica
  • 127,356
  • 13
  • 118
  • 231