简体   繁体   中英

objective-c round number to nearest 50

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

ie 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...

PS Im using cocoa-touch for the iPhone

Thanks a lot Mark

做这个:

50.0 * floor((Number/50.0)+0.5)

除以50,舍入到最接近的整数,然后乘以50。

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);
    }
}

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

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

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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM