Replace truthiness guard with Number.isFinite() so NaN and Infinity are explicitly rejected rather than silently masked. Zero is now handled by toLocaleString, which returns '0' correctly. Add test cases for NaN and Infinity.
33 lines
1.2 KiB
TypeScript
33 lines
1.2 KiB
TypeScript
import { formatUnits } from 'viem';
|
|
|
|
/** Convert wei (bigint or string) to a JS number. Core primitive. */
|
|
export function weiToNumber(value: bigint | string, decimals = 18): number {
|
|
const bi = typeof value === 'string' ? BigInt(value || '0') : (value ?? 0n);
|
|
return Number(formatUnits(bi, decimals));
|
|
}
|
|
|
|
/** Format wei to fixed decimal string (e.g. "0.00123") */
|
|
export function formatWei(value: bigint | string, decimals = 18, digits = 5): string {
|
|
const num = weiToNumber(value, decimals);
|
|
return num === 0 ? '0' : num.toFixed(digits);
|
|
}
|
|
|
|
/** Format number to compact display (e.g. "1.23K", "4.56M") */
|
|
export function compactNumber(value: number): string {
|
|
return Intl.NumberFormat('en-US', {
|
|
notation: 'compact',
|
|
maximumFractionDigits: 2,
|
|
}).format(value);
|
|
}
|
|
|
|
/** Format number with commas (e.g. "1,234,567") */
|
|
export function commaNumber(value: number): string {
|
|
if (!Number.isFinite(value)) return '0';
|
|
return value.toLocaleString('en-US');
|
|
}
|
|
|
|
/** Format a token amount with comma grouping and 2 decimal places (e.g. "1,234.56") */
|
|
export function formatTokenAmount(value: number): string {
|
|
if (!isFinite(value)) return '0.00';
|
|
return value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
}
|