Rounding without inline method

I want to round a float variable to int without using an inline method. It will look like

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

So far this is the closest thing I could get to, but I'm not sure if it is effective.

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

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

}
+4
source share
3 answers

You can try the following:

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

There is a trick with negative values ​​(you cannot just add 0.5):

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

And be careful, as

  int.MaxValue < float.MaxValue
  int.MinValue > float.MinValue
+5
source

Well, you already use casting, and sometimes it can give you exactly what you need. If you just add 0.5 to your number and then produce an integer, you get a 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

Here is how you could write a method.

int Roundoff(float num)
{
    return (int) (num + 0.5);
}
+4
source
float f = 0.3;  // Or whatever
int i = (int) (f + 0.5f);
+1

Source: https://habr.com/ru/post/1533306/


All Articles