Search code examples
objective-cmathios5

Round Numbers Evenly


How do I round numbers up or down depending on the value in object C.. for example.

Lets say the number is 143 - I would want to round down to 140 but if the number is 146 - I would want to round up to 150

any suggestions?


Solution

  • Assuming 145 should round to 150 (that's the standard in science and technology), the formula is:

    x_rounded = ((x + 5)/10)*10;
    

    More generally, when rounding to the nearest n, it's

    x_rounded = ((x + n/2)/n)*n;
    

    It comes from the fact that integer division always rounds down.

    For negative numbers, it's slightly more tricky.

    EDIT: also assuming it's all integers. With floats/doubles, better use the C math library, as division works differently. Like this:

    #include <math.h>
    
    x_rounded = floor((x+5)/10) * 10;