Math.Round function

CoderSource.net
Math.Round function - Article by aliasgar
Rating:

Date: 6/15/2005 6:15:21 PM

I had the below problem with the Math.Round() function:

Problem :

  When I use the Math.Round Function it uses the Bankers Method. (ie., Round(5.5) = 5 and Round(5.50001) = 6). But when I use the Format String  "{0:F0}" it uses the proper Mathematical Method.(ie. Round(5.5)=6). Why this inconsistency followed in .NET?

    Is any other way to switch the Math.Round function from Bankers Method to Mathematical Method?  or  Is any other way to switch the Format String "{0:F0}" from Mathematical Method to Bankers Method?

Solution:

   I had to write my own function. The built-in Round function uses banker's rounding to round to the nearest EVEN digit when the LSD is a 5. Here is one solution to always rounding up when the least significant digit is a 5:

static void Main(string[] args)
{

double num; int place; string snum;

Console.Write("Enter positive or negative number to round: ");

snum = Console.ReadLine();

if (snum == "") snum = "0";

num = Convert.ToDouble(snum);

Console.Write("Number of places to round right or left (-) of decimal: ");

snum = Console.ReadLine();

if (snum == "") snum = "0";

place = Convert.ToInt32(snum);

Console.WriteLine("\nThe rounded number is {0}", roundnum(num, place));

Console.WriteLine();

}

public static double roundnum(double num, int place)
{

double n;

n = num * Math.Pow(10, place);

n = Math.Sign(n) * Math.Abs(Math.Floor(n + .5));

return n / Math.Pow(10, place);

}

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us