harb/kraiken-lib/src/format.ts
openhands 8c43d3890c fix: Move BigInt formatting functions from helper.ts to kraiken-lib/format (#246)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-24 23:00:58 +00:00

26 lines
947 B
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';
}