Skip to content

Commit

Permalink
fix(type): use number | bigint
Browse files Browse the repository at this point in the history
  • Loading branch information
Rubilmax committed Dec 20, 2023
1 parent a20e6db commit d3cac04
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
18 changes: 11 additions & 7 deletions src/format.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { pow10 } from "./utils";

export const format = (x: bigint, decimals: number = 18, digits?: number) => {
decimals = Math.floor(decimals);
digits = Math.floor(digits ?? decimals);
export const format = (x: bigint, decimals: number | bigint = 18, digits?: number | bigint) => {
decimals = Math.floor(Number(decimals));
digits = Math.floor(Number(digits ?? decimals));

if (decimals === 0) return x.toString();

Expand All @@ -23,16 +23,20 @@ export const format = (x: bigint, decimals: number = 18, digits?: number) => {
return full;
};

export const toFloat = (x: bigint, decimals?: number) => {
export const toFloat = (x: bigint, decimals?: number | bigint) => {
return parseFloat(format(x, decimals));
};

export const toDecimals = (x: bigint, decimals: number, scaleDecimals: number) => {
export const toDecimals = (
x: bigint,
decimals: number | bigint,
scaleDecimals: number | bigint,
) => {
if (decimals <= scaleDecimals) {
const ratio = pow10(BigInt(Math.floor(scaleDecimals - decimals)));
const ratio = pow10(BigInt(Math.floor(Number(scaleDecimals) - Number(decimals))));

return (x + ratio / 2n) / ratio;
}

return x * pow10(BigInt(Math.floor(decimals - scaleDecimals)));
return x * pow10(BigInt(Math.floor(Number(decimals) - Number(scaleDecimals))));
};
4 changes: 2 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export type MulDiv = (x: bigint, y: bigint, scale: bigint) => bigint;

export const pow10 = (power: bigint) => {
return 10n ** power;
export const pow10 = (power: number | bigint) => {
return 10n ** BigInt(power);
};

export const approxEqAbs = (x: bigint, y: bigint, tolerance: bigint = 0n) => {
Expand Down

0 comments on commit d3cac04

Please sign in to comment.