I have the following class
public static class MyClass
{
public static double Converter(int mpg)
{
return Math.Round((double)mpg / ((double)36 / 12.74), 2);
}
}
And NUnit unit test
[TestFixture]
public class ConverterTests
{
[Test]
public void Basic_Tests()
Assert.AreEqual(8.50, MyClass.Converter(24));
}
}
My Unit tests fails with
Expected: 8.5d
But was: 8.4900000000000002d
When I debug the method return 8.49 so where does the unit test get the long number from with a 2 at the end?
The unit test shows the same result as I see when executing the code. Here's a short but complete program to show the exact result retrieved, using my DoubleConverter
class.
using System;
class Test
{
static void Main()
{
double x = Convert(24);
Console.WriteLine(DoubleConverter.ToExactString(x));
}
static double Convert(int mpg)
{
return Math.Round((double) mpg / ((double) 36 / 12.74), 2);
}
}
Result:
8.4900000000000002131628207280300557613372802734375
Using a calculator, I'd expect the unrounded result to be 8.4933333 - which would indeed round to "about 8.49" when rounded to two decimal places.
So really, the question is more why you're seeing 8.5 in the debugger than why the unit test fails. I'm not seeing that myself, so you might want to look into exactly how you're debugging. When you debug, you may be seeing different results because:
See more on this question at Stackoverflow