Comparing numbers approximately in QunitJS

JS is prone to floating point errors. A classical example is: 0.1 + 0.2 = 0.30000000000000004 Often when it comes to testing you want to check if resulting numbers are pretty close. You can simply do it in QunitJS by defining a new assertion as follows:

/**
 * Compare numbers taking in account an error
 *
 * @param  {Float} number
 * @param  {Float} expected
 * @param  {Float} error    Optional
 * @param  {String} message  Optional
 */
QUnit.assert.close = function(number, expected, error, message) {
  if (error === void 0 || error === null) {
    error = 0.00001 // default error
  }

  var result = number == expected || (number < expected + error && number > expected - error) || false

  QUnit.push(result, number, expected, message);
}

Now instead of assert.equal(0.1 + 0.2, 0.3) you should do assert.close(0.1 + 0.2, 0.3) and your test will pass. If you want to control the precision then you pass as third argument max error value.

You may check out this library that has the same method and few more.