Search code examples
c#.netmathroundingfloor

Is there a way to floor/ceil based on whether the value is over 0.5 or under?


I am trying to round my values so that if it's 0.5 or greater, it becomes 1, else it becomes 0. For example:

3.7 -> 4;
1.3 -> 1;
2.5 -> 3;
...

Any ideas?


Solution

  • Math.Round(3.7,MidpointRounding.AwayFromZero);
    

    http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx

    In the above, I made use of AwayFromZero for rounding because the default is Banker's rounding, so if the fraction is 0.5, it is rounded to nearest even. So 3.5 becomes 4 (nearest even), but 2.5 becomes 2 (nearest even). So you choose a different method as shown above to make 3.5 to 4 and 2.5 to 3.