Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roundoff without builtin method

Tags:

c#

rounding

I want to roundoff a float variable to int, without using any builtin method. This will be like

13.4 => 13
13.49 => 13
13.5 => 14
13.6 => 14

So far this is the closest I could reach to but not sure if this is efficient.

int Roundoff(float num)
{
    int temp = (int) num;

    num *= 10;
    if(num%10 >= 5)
    {
        return temp + 1;
    }
    else
    {
        return temp;
    }

}
like image 708
user3459107 Avatar asked Dec 26 '22 11:12

user3459107


2 Answers

You can try this:

int Roundoff(float num) {
  return num < 0 ? (int) (num - 0.5) : (int) (num + 0.5);
}

There is a trick with negative values (you can't just add 0.5):

  -13.9 -> -14.0
  -13.1 -> -13

And be careful, since

  int.MaxValue < float.MaxValue
  int.MinValue > float.MinValue
like image 184
Dmitry Bychenko Avatar answered Jan 02 '23 16:01

Dmitry Bychenko


Well you are already using casting and sometime this can give you exactly what you need. If you simply add 0.5 in your number and then cast to integer, you will get the rounded value.

13.4 + 0.5 = 13.9 -> 13 (when casted to int)
13.49 + 0.5 = 13.99 -> 13
13.5 + 0.5 = 14.0 -> 14
13.6 + 0.5 = 14.1 -> 14

This is how you would write the method.

int Roundoff(float num)
{
    return (int) (num + 0.5);
}
like image 44
Riz Avatar answered Jan 02 '23 18:01

Riz