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
How to "round" a float to an int?
3 Answers
Know the answer? Post it. Somebody with the same question will find it here.

Mamta MRank #268 · 9.4K reputationPosted Jan 4, 2011, 6:52 PM EST
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.
Blocked AccountRank #403 · 6.2K reputationPosted Jan 4, 2011, 7:09 PM EST
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.
Peter14 reputationPosted Jan 4, 2011, 7:31 PM EST