Skip to content

Commit

Permalink
feat: add common formatters
Browse files Browse the repository at this point in the history
  • Loading branch information
toniocodo committed Sep 13, 2023
1 parent 65e5b6f commit 2150d7c
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions libs/shared/utils/src/formatters.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,48 @@
import { formatUnits } from 'viem';

import type { FormatNumberOptions } from 'react-intl';

export const middleTruncate = (address: string, start = 6, end = 4): string =>
`${address.slice(0, start)}${address.slice(-end)}`;

export const valueFormat: FormatNumberOptions = {
minimumFractionDigits: 2,
};

export const currencyFormat: FormatNumberOptions = {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
};

export const quantityFormat: FormatNumberOptions = {
minimumFractionDigits: 0,
maximumFractionDigits: 4,
};

// Format map [value, maxDigits]
const mappings = [
[10000000, 0],
[100000, 1],
[100, 2],
[1, 3],
[0.1, 4],
[0.0001, 5],
[0.000001, 6],
] as const;

export function formatAmount(amount: bigint, decimals = 18) {
if (!amount || amount === 0n) return '0';

const amt = +formatUnits(amount, decimals);

for (const [threshold, maxDigits] of mappings) {
if (amt >= threshold) {
return amt.toLocaleString('en', {
maximumFractionDigits: maxDigits,
});
}
}

return '~ 0';
}

0 comments on commit 2150d7c

Please sign in to comment.