Hi all,
I knocked up a quick program to divide marks by 2. I wanted to round to 2 decimal places. My code is:
static void Main(string[] args)
{
double a, b;
Console.Write("Enter mark:");
a = double.Parse(Console.ReadLine());
while (a != -1)
{
b = a / 2.0;
b = Math.Round(b, 2, MidpointRounding.AwayFromZero);
Console.WriteLine(b + "\n");
Console.WriteLine("Enter mark:");
a = double.Parse(Console.ReadLine());
}
Console.ReadLine();
}
The thing that I do not get - when I enter 36.05, it outputs 18.02. Now, 36.05 / 2.0 equals 18.025. So my question is, why doesn't Math.Round successfully round that up to 18.03?
There's no hassle or rush on this. It is just a point of curiosity for me. I don't like it when I cannot figure out why I don't get an expected result.
Cheers
Loading
DavePosted Apr 29, 2008, 8:31 AM
Thanks very much for pointing me in the right direction. Changing the variables to the decimal type has rectifed the problem. And more importantly, I understand why. Cheers.
AlanPosted Apr 29, 2008, 7:27 AM
This is just one of the vagaries of floating point arithmetic due to not all decimal numbers having an exact representation in binary. See for example this other recent thread:
http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=40596
What may be happening here is that when the double value of 18.025 is converted internally to 10 byte precision, the result is very slightly less than 18.025 and hence it get rounded to 18.02.
The problem with this stuff is that you never know when it's going to occur. If your application cannot tolerate inconsistencies of this sort , then it's best to use the decimal type instead of double. However, decimals require twice as much as memory and are much slower when you have thousands of calculations to do.