Niek
Niek

Reputation: 1030

Round off whole number in C

I have a number (00-59) in an int and i would like to round it off to 5, for example 06 would be 5 and 08 would be 10. Oh and 07 would also be 10. How would i go about doing this?

Upvotes: 0

Views: 1907

Answers (8)

Julien Fouilhé
Julien Fouilhé

Reputation: 2658

If you want to code your own round function, here is something that should work:

int round(int number, int round_by)
{
    int whole = number / round_by;
    char superior = ((number % round_by) >= (round_by / 2)) ? 1 : 0;
    return (whole + superior) * round_by;
}

int main()
{
    printf("%d\n", round(6, 5)); // 5
    printf("%d\n", round(7, 5)); // 10
    printf("%d\n", round(8, 5)); // 10
    printf("%d\n", round(33, 10)); // 30
    printf("%d\n", round(33, 5)); // 35
}

You can replace 5 by every number you want.

Upvotes: 2

vCillusion
vCillusion

Reputation: 1799

You can use the following code:

//no -> number  ro -> round off to
//ro = 5 in your case
int no, ro;
if(no%ro >= 2)
    no = ((no/ro)+1)*ro;
else
    no = (no/ro)*ro;

Hope it helps !!

Upvotes: 0

Eregrith
Eregrith

Reputation: 4366

Use the formula

rounded = (number / 5) * 5;
if ((number % 5) > 1)
  rounded += 5;

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476990

This should work:

unsigned int round5(unsigned int n)
{
    return ((n + 2) / 5) * 5;
}

(Say + 3 if you want to round 7 up, though this would seem unnatural.)

Upvotes: 0

CCoder
CCoder

Reputation: 2335

You can use the following code.

int round_5(int num)
{
   int t1;
   t1= num%5;
   if(t1>=2)
      num+=(5-t1);
   else
      num-=t1;
   return num;
}


main()
{
   int num = 57;
   num = round_5(num);
   printf("%d",num);
   return 0;
}

Hope this helps.

Upvotes: 6

Aki Suihkonen
Aki Suihkonen

Reputation: 20027

How about a look up table

int minutes [60] = { 0,0,0,5,5,5,5,5,10,10,10, ... };

Upvotes: 0

cdhowie
cdhowie

Reputation: 168988

If you're willing to delve into the floating-point realm, you can do something like this:

int rounded = (int)(round((float)input / 5) * 5);

Make sure you #include <math.h>. See this ideone example.

Upvotes: 0

PhonicUK
PhonicUK

Reputation: 13854

This isn't C specific but the idea works the same:

func roundToNearest(num someNumber, num roundToNearest)
{
    return (round(someNumber / roundToNearest) * roundToNearest);
}

This is just pseudocode of course, in the case of C you'll need to be casting to singles to get anything useful out of it.

In the case of c, round comes from math.h

Upvotes: 0

Related Questions