Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding integers to nearest ten or hundred in C

Tags:

c

rounding

I'm trying to think of a function in C that would satisfy the following conditions:

  • It accepts an integer greater than 0 as an argument;
  • It rounds that integer up to the nearest value so that only the first digit is not a zero

For example:

53 comes out as 60..

197 comes out as 200..

4937 comes out as 5000..

Is there a way to do this so that the requirement is satisfied regardless of the number of trailing zeroes?

For example, I understand how I could do it in any individual case. divide 53 by 10 then ceil(), multiply by 10, but I would like one that can handle any value.

Opinions? Ideas?

like image 545
M. Ryan Avatar asked Jan 15 '13 18:01

M. Ryan


1 Answers

Avoid string conversions and loops:

int num = ... // your number
int len = log10(num);
float div = pow(10, len);
int rounded = ceil(num / div) * div;
like image 114
rmaddy Avatar answered Sep 21 '22 16:09

rmaddy