UNPKG

@shogun-sdk/money-legos

Version:

Shogun Money Legos: clients and types for quotes, memes, prices, balances, fees, validations, etc.

58 lines (42 loc) 1.86 kB
import { type BigNumberish } from 'ethers'; export function formatUnits(value: string, decimals: number) { let display = value.toString(); const negative = display.startsWith('-'); if (negative) display = display.slice(1); display = display.padStart(decimals, '0'); const integer = display.slice(0, display.length - decimals); let fraction = display.slice(display.length - decimals); fraction = fraction.replace(/(0+)$/, ''); return `${negative ? '-' : ''}${integer || '0'}${fraction ? `.${fraction}` : ''}`; } export const SOLANA_LAMPORTS_DECIMALS = 9; export function formatEthDecimal(value: bigint | BigNumberish, precision = 2, decimals = 18) { const data = Number(formatUnits(value.toString(), decimals)); if (data === 0) return '0'; let fixed = data.toFixed(precision); fixed = fixed.replace(/(\.\d*?[1-9])0+$/g, '$1').replace(/\.0+$/, ''); if (precision === 0) { fixed = Math.round(data).toString(); } if (fixed === '' || fixed === '-0' || fixed === '-') return '0'; return fixed; } export function numberWithCommas(value: number, precision: number) { const fixedNumber = value.toFixed(precision); const parts = fixedNumber.split('.'); const withCommas = (parts[0] || '0').replace(/\B(?=(\d{3})+(?!\d))/g, ','); return parts[1] ? withCommas + '.' + parts[1] : withCommas; } export function formatCmpctNumber(number: number): string { // Only apply compact formatting for numbers 1 million or greater if (Math.abs(number) >= 1_000_000) { const usFormatter = new Intl.NumberFormat('en-US', { notation: 'compact', compactDisplay: 'short', maximumFractionDigits: 2, // Limit to one decimal place }); return usFormatter.format(number); } // Return numbers below 1 million without compact notation, with comma formatting return number.toLocaleString('en-US'); }