Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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?

  • Leaders
Posted

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 :).

Iceplug, USN

One of my coworkers thinks that I believe that drawing bullets is the most efficient way of drawing bullets. Whatever!!! :-(

Posted

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

  • *Experts*
Posted

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

"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
Posted

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,

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...