DeFlipMode Posted July 8, 2004 Posted July 8, 2004 VB.NET's Math.Round() seems to be a Round_Half_Even as the data below shows: (5.5 rounds to 6.0, and 6.5 rounds to 6.0) ?math.round(5.2) 5.0 ?math.round(5.5) 6.0 ?math.round(5.8) 6.0 ?math.round(6.0) 6.0 ?math.round(6.5) 6.0 Is there an easy way to create a Round_Half_Up so that 5.5 rounds to 6.0 and 6.5 rounds to 7.0? I can think of a number of ways to do this by testing, but not sure if .NET has this built in and I just can't find it in the documentaion. Any Ideas? Quote
Leaders Iceplug Posted July 8, 2004 Leaders Posted July 8, 2004 The only way that I can think of is this: ?Math.Floor(N + 0.5) The rounding thing has something to do with statistical accuracy... The average of 5.5 and 6.5 is 6, rounding both numbers up will give you 6.5 as the average, but rounding towards even, as the .Round function, and most computer rounding algorithms, wil give you the average of 6, and similarly, you get 5 from 4.5 and 5.5 :). Quote Iceplug, USN One of my coworkers thinks that I believe that drawing bullets is the most efficient way of drawing bullets. Whatever!!! :-(
DeFlipMode Posted July 8, 2004 Author Posted July 8, 2004 Thanks!! Looking at your method makes me think... Duh... why didn't I think of that! :rolleyes: That is a lot easier than the method I was going to use, and more accurate. Glad I asked. :D Quote
*Experts* Nerseus Posted July 8, 2004 *Experts* Posted July 8, 2004 If you need to worry about negative numbers, you'll need to use Ceiling. Here's a function I use which takes a decimal. Feel free to change it for use with double or other types. public static decimal RoundUpToWholeNumber(decimal val) { if(val<decimal.Zero) return (decimal)Math.Ceiling((double)val - 0.5); else return (decimal)Math.Floor((double)val + 0.5); } -nerseus Quote "I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
DeFlipMode Posted July 9, 2004 Author Posted July 9, 2004 Thanks for the additional info! For the behavior I required, the Math.Floor(N+0.5) tested fine for both positive and negative numbers.... but always nice to know more than you need. :cool: Later, Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.