Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare decimals knowing there is room for error

I have two different ways to calculate a value. Once both methods run, I get the following:

decimal a = 145.2344;
decimal b = 145.2345;

I have a unit test:

  Assert.AreEqual(a,b);

I want to be able to account for a +/- .0001 difference. How can I add this rule?

like image 977
RJP Avatar asked Dec 28 '12 19:12

RJP


People also ask

How do you tell if a decimal is greater than another?

The greater a decimal is, the closer it is to one whole. The smaller a decimal is the farther it is from one whole. The first thing you need to look at is the digit number in each decimal. These each have two digits in them, so you can compare them right away.


2 Answers

In NUnit's constraint model, you can do this:

Assert.That(Math.Abs(a-b), Is.LessThan(0.0001M));

Better yet, make it a function:

void AssertDiff(decimal a, decimal b, decimal diff = 0.0001) {
     Assert.That(Math.Abs(a-b), Is.LessThan(diff));
}

EDIT : In MS Unit Test Framework, do this:

void AssertDiff(decimal a, decimal b, decimal diff = 0.0001) {
     Assert.IsTrue(Math.Abs(a-b) < diff);
}
like image 89
Sergey Kalinichenko Avatar answered Oct 24 '22 12:10

Sergey Kalinichenko


Simple:

if (Math.Abs(a-b) < 0.0001m)
    // equal
like image 39
Jonathon Reinhart Avatar answered Oct 24 '22 10:10

Jonathon Reinhart