How do I find if two variables are approximately equals?

Viewed 46857

I am writing unit tests that verify calculations in a database and there is a lot of rounding and truncating and stuff that mean that sometimes figures are slightly off.

When verifying, I'm finding a lot of times when things will pass but say they fail - for instance, the figure will be 1 and I'm getting 0.999999

I mean, I could just round everything into an integer but since I'm using a lot of randomized samples, eventually i'm going to get something like this

10.5 10.4999999999

one is going to round to 10, the other will round to 11.

How should I solve this problem where I need something to be approximately correct?

6 Answers

In NUnit, I like the clarity of this form:

double expected = 10.5;
double actual = 10.499999999;
double tolerance = 0.001;
Assert.That(actual, Is.EqualTo(expected).Within(tolerance));

The question was asking how to assert something was almost equal in unit testing. You assert something is almost equal by using the built-in Assert.AreEqual function. For example:

Assert.AreEqual(expected: 3.5, actual : 3.4999999, delta:0.1);

This test will pass. Problem solved and without having to write your own function!

Related