From 1942eaa72f7c4e375a253ad12a426fd30f22d748 Mon Sep 17 00:00:00 2001 From: mmaurello <93129175+mmaurello@users.noreply.github.com> Date: Mon, 6 Feb 2023 16:29:05 +0100 Subject: [PATCH] Add round type to toDecimal function (#57) * add rounding type to toDecimal function * add unit test for roundint types --- packages/utils/src/numbers/decimals.test.ts | 15 +++++++++++++++ packages/utils/src/numbers/decimals.ts | 5 +++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/utils/src/numbers/decimals.test.ts b/packages/utils/src/numbers/decimals.test.ts index 5da6bfc4..90ed5f90 100644 --- a/packages/utils/src/numbers/decimals.test.ts +++ b/packages/utils/src/numbers/decimals.test.ts @@ -1,4 +1,5 @@ /* eslint-disable jest/max-expects */ +import Big from 'big.js'; import { toBigInt, toDecimal } from './decimals'; describe('utils - decimals', () => { @@ -42,6 +43,20 @@ describe('utils - decimals', () => { expect(toDecimal('711_158_793', 9, 9)).toBe(0.711158793); expect(toDecimal('711_158_793n', 9, 9)).toBe(0.711158793); }); + + it('should convert to decimals with the correct rounding types', () => { + expect(toDecimal(477_844_894, 9, 0)).toBe(0); + expect(toDecimal(370_024_965_982_774n, 12, 1, Big.roundDown)).toBe(370); + expect(toDecimal(477_844_894, 9, 0, Big.roundUp)).toBe(1); + expect(toDecimal('167_850_000n', 9, 4, Big.roundHalfEven)).toBe(0.1678); + expect(toDecimal('7_117_587_933_365_016_000', 18, 2)).toBe(7.12); + expect(toDecimal('7_117_587_933_365_016_000', 18, 2, Big.roundDown)).toBe( + 7.11, + ); + expect( + toDecimal('7_117_587_933_365_016_000', 18, 2, Big.roundHalfUp), + ).toBe(7.12); + }); }); describe('toBigInt', () => { diff --git a/packages/utils/src/numbers/decimals.ts b/packages/utils/src/numbers/decimals.ts index 0d65bb07..fcd47edd 100644 --- a/packages/utils/src/numbers/decimals.ts +++ b/packages/utils/src/numbers/decimals.ts @@ -1,13 +1,14 @@ -import Big from 'big.js'; +import Big, { RoundingMode } from 'big.js'; export function toDecimal( number: bigint | number | string, decimals: number, maxDecimal = 6, + roundType?: RoundingMode, ): number { const dividend = Big(number.toString().replace(/[^0-9]/g, '')); const divisor = Big(10).pow(decimals); - const result = dividend.div(divisor).round(maxDecimal); + const result = dividend.div(divisor).round(maxDecimal, roundType); return result.toNumber(); }