From: Jérôme Benoit Date: Sat, 1 Jul 2023 19:41:48 +0000 (+0200) Subject: fix: fix roundTo() corner cases X-Git-Tag: v1.2.18~87 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=316d1564060a88932a006299a12f621d64a0320f;p=e-mobility-charging-stations-simulator.git fix: fix roundTo() corner cases Signed-off-by: Jérôme Benoit --- 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);