objective-c round number to nearest 50
How can I round a number to the nearest X value (for example 50)
i.e 47 w开发者_如何学编程ould 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
Do this:
50.0 * floor((Number/50.0)+0.5)
Divide by 50, round to the nearest integer, and multiply by 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;
}
精彩评论