From c604012793c23cb9de3ca270dec6d0dce734d65f Mon Sep 17 00:00:00 2001 From: Pierre Vanduynslager Date: Sun, 25 Jun 2017 16:59:24 -0400 Subject: [PATCH] Fix rounding in toBeCloseTo --- spec/core/matchers/toBeCloseToSpec.js | 26 ++++++++++++++++++++++++++ src/core/matchers/toBeCloseTo.js | 3 ++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/spec/core/matchers/toBeCloseToSpec.js b/spec/core/matchers/toBeCloseToSpec.js index a0eca07f..bf04c153 100644 --- a/spec/core/matchers/toBeCloseToSpec.js +++ b/spec/core/matchers/toBeCloseToSpec.js @@ -8,6 +8,9 @@ describe("toBeCloseTo", function() { result = matcher.compare(0, 0.001); expect(result.pass).toBe(true); + + result = matcher.compare(0, 0.005); + expect(result.pass).toBe(true); }); it("fails when not within two decimal places by default", function() { @@ -16,6 +19,9 @@ describe("toBeCloseTo", function() { result = matcher.compare(0, 0.01); expect(result.pass).toBe(false); + + result = matcher.compare(0, 0.05); + expect(result.pass).toBe(false); }); it("accepts an optional precision argument", function() { @@ -25,8 +31,20 @@ describe("toBeCloseTo", function() { result = matcher.compare(0, 0.1, 0); expect(result.pass).toBe(true); + result = matcher.compare(0, 0.5, 0); + expect(result.pass).toBe(true); + result = matcher.compare(0, 0.0001, 3); expect(result.pass).toBe(true); + + result = matcher.compare(0, 0.0005, 3); + expect(result.pass).toBe(true); + + result = matcher.compare(0, 0.00001, 4); + expect(result.pass).toBe(true); + + result = matcher.compare(0, 0.00005, 4); + expect(result.pass).toBe(true); }); it("fails when one of the arguments is null", function() { @@ -58,7 +76,15 @@ describe("toBeCloseTo", function() { result = matcher.compare(1.23, 1.225); expect(result.pass).toBe(true); + result = matcher.compare(1.23, 1.235); + expect(result.pass).toBe(true); + + // 1.2249999 will be rounded to 1.225 result = matcher.compare(1.23, 1.2249999); + expect(result.pass).toBe(true); + + // 1.2249999 will be rounded to 1.224 + result = matcher.compare(1.23, 1.2244999); expect(result.pass).toBe(false); result = matcher.compare(1.23, 1.234); diff --git a/src/core/matchers/toBeCloseTo.js b/src/core/matchers/toBeCloseTo.js index 94f7c4ec..7cd2b76f 100644 --- a/src/core/matchers/toBeCloseTo.js +++ b/src/core/matchers/toBeCloseTo.js @@ -21,8 +21,9 @@ getJasmineRequireObj().toBeCloseTo = function() { ); } + var pow = Math.pow(10, precision + 1); return { - pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2) + pass: +(Math.round(Math.abs(expected - actual) * pow) / pow).toFixed(precision + 1) <= (Math.pow(10, -precision) / 2) }; } };