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;
}
}
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With