From 316d1564060a88932a006299a12f621d64a0320f Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sat, 1 Jul 2023 21:41:48 +0200 Subject: [PATCH] fix: fix roundTo() corner cases MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/utils/Utils.ts | 7 +------ test/utils/Utils.test.ts | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index c86afeca..04b40d30 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -142,12 +142,7 @@ export class Utils { public static roundTo(numberValue: number, scale: number): number { const roundPower = Math.pow(10, scale); - return Math.round(numberValue * roundPower) / roundPower; - } - - public static truncTo(numberValue: number, scale: number): number { - const truncPower = Math.pow(10, scale); - return Math.trunc(numberValue * truncPower) / truncPower; + return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower; } public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number { diff --git a/test/utils/Utils.test.ts b/test/utils/Utils.test.ts index 5732e57e..60d2e2ae 100644 --- a/test/utils/Utils.test.ts +++ b/test/utils/Utils.test.ts @@ -134,6 +134,21 @@ describe('Utils test suite', () => { expect(randomInteger).toBeLessThanOrEqual(Math.floor(max)); }); + it('Verify roundTo()', () => { + expect(Utils.roundTo(0, 2)).toBe(0); + expect(Utils.roundTo(0.5, 0)).toBe(1); + expect(Utils.roundTo(0.5, 2)).toBe(0.5); + expect(Utils.roundTo(-0.5, 0)).toBe(-1); + expect(Utils.roundTo(-0.5, 2)).toBe(-0.5); + expect(Utils.roundTo(1.005, 0)).toBe(1); + expect(Utils.roundTo(1.005, 2)).toBe(1.01); + expect(Utils.roundTo(2.175, 2)).toBe(2.18); + expect(Utils.roundTo(5.015, 2)).toBe(5.02); + expect(Utils.roundTo(-1.005, 2)).toBe(-1.01); + expect(Utils.roundTo(-2.175, 2)).toBe(-2.18); + expect(Utils.roundTo(-5.015, 2)).toBe(-5.02); + }); + it('Verify getRandomFloat()', () => { let randomFloat = Utils.getRandomFloat(); expect(typeof randomFloat === 'number').toBe(true); -- 2.34.1