Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-c round number to nearest 50

How can I round a number to the nearest X value (for example 50)

i.e 47 would be 50

24 would be 0

74 would be 50

99 would be 100

etc...

I really have no idea where to start looking into how to do this...

P.S. Im using cocoa-touch for the iPhone

Thanks a lot Mark

like image 819
Mark Avatar asked Jul 19 '10 23:07

Mark


5 Answers

Do this:

50.0 * floor((Number/50.0)+0.5)
like image 111
David Skrundz Avatar answered Oct 19 '22 04:10

David Skrundz


Divide by 50, round to the nearest integer, and multiply by 50.

like image 45
dan04 Avatar answered Oct 19 '22 04:10

dan04


So, combining what've been said here, here is general function:

float RoundTo(float number, float to)
{
    if (number >= 0) {
        return to * floorf(number / to + 0.5f);
    }
    else {
        return to * ceilf(number / to - 0.5f);
    }
}
like image 21
ivanzoid Avatar answered Oct 19 '22 05:10

ivanzoid


If number is positive: 50 * floor( number / 50 + 0.5 );

If number is negative: 50 * ceil ( number / 50 - 0.5 );

like image 29
RobertL Avatar answered Oct 19 '22 05:10

RobertL


I'd like to propose a less elegant, though more precise solution; it works for even target numbers only.

This example rounds a given number of seconds to the next full 60:

int roundSeconds(int inDuration) {

    const int k_TargetValue = 60;
    const int k_HalfTargetValue = k_TargetValue / 2;

    int l_Seconds = round(inDuration);                           // [MININT .. MAXINT]
    int l_RemainingSeconds = l_Seconds % k_TargetValue;          // [-0:59 .. +0:59]
    if (ABS(l_RemainingSeconds) < k_HalfTargetValue) {           // [-0:29 .. +0:29]
        l_Seconds -= l_RemainingSeconds;                         // --> round down
    } else if (l_RemainingSeconds < 0) {                         // [-0:59 .. -0:30]
        l_Seconds -= (k_TargetValue - ABS(l_RemainingSeconds));  // --> round down
    } else {                                                     // [+0:30 .. +0:59]
        l_Seconds += (k_TargetValue - l_RemainingSeconds);       // --> round up
    }

    return l_Seconds;
 }
like image 41
Dirk Stegemann Avatar answered Oct 19 '22 03:10

Dirk Stegemann