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);
}
|