In my iPhone app I need to round an integer to the nearest multiple of 5.
E.g. Round 6 to = 10 and round 23 to = 25 etc
I forgot to say, I only want to round up! In all situations, so 22 would round up to 25 for example.
If you want to always round up, you can use the following:
int a = 22;
int b = (a + 4) / 5 * 5; // b = 25;
If a
can be a float, you should add a cast to int
as follows:
int b = ((int)a + 4) / 5 * 5; // b = 25;
Note that you can use the function ceil
to accomplish the same result:
int a = 22;
int b = ceil((float)a / 5) * 5; // b = 25;
Old Answer:
To round to the nearest multiple of 5
, you can do the following:
int a = 23;
int b = (int)(a + 2.5) / 5 * 5;