harb/kraiken-lib/src/format.ts
openhands 8f5910d30a fix: Raw number rendering for \taxPaidGes\ and \profit\ after load (#375)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 03:03:22 +00:00

31 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 {
return value ? value.toLocaleString('en-US') : '0';
}
/** Format a token amount with comma grouping and 2 decimal places (e.g. "1,234.56") */
export function formatTokenAmount(value: number): string {
return value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}