Hi
how do I round a float to an int, such that if the decimal part is .5 or more, then the value is rounded up, otherwise the value is rounded down?
For example, 3.2f => 3; 3.5f => 4; 3.7f => 4; 4.2f => 4; 4.5f => 5; 4.7f => 5
If I use (int)Math.Round(3.5f), the result is 4 (ie what I want); whereas with (int)Math.Round(4.5f), the result is 4 (ie not what I want).
Is there a "Math" method which does rounding the way I want it?
Thanks,
Peter
Loading
Mamta MPosted Jan 4, 2011, 11:52 PM
What you need is
(int)Math.Round(4.5f, MidpointRounding.AwayFromZero)
This will return you 5 as you desire.
More on the MidPointRounding can be found here
http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
Hope that helps.
PeterPosted Jan 5, 2011, 12:31 AM
Blocked AccountPosted Jan 5, 2011, 12:09 AM
Math.Round is working like that as you want. I checked that.
it gives (int)Math.Round(7.5f) result = 8
and when i put (int)Math.Round(7.4f) result= 7
I think this is you want. And It works perfect.