Skip to content

Commit

Permalink
Add round type to toDecimal function (#57)
Browse files Browse the repository at this point in the history
* add rounding type to toDecimal function

* add unit test for roundint types
  • Loading branch information
mmaurello authored Feb 6, 2023
1 parent 77664b2 commit 1942eaa
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
15 changes: 15 additions & 0 deletions packages/utils/src/numbers/decimals.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable jest/max-expects */
import Big from 'big.js';
import { toBigInt, toDecimal } from './decimals';

describe('utils - decimals', () => {
Expand Down Expand Up @@ -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', () => {
Expand Down
5 changes: 3 additions & 2 deletions packages/utils/src/numbers/decimals.ts
Original file line number Diff line number Diff line change
@@ -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();
}
Expand Down

0 comments on commit 1942eaa

Please sign in to comment.