// 数字格式化工具 export const numberUtils = { // 格式化数字,添加千分位分隔符 format: (num: number, decimalPlaces: number = 0): string => { if (isNaN(num)) return '0'; return num.toFixed(decimalPlaces).replace(/\B(?=(\d{3})+(?!\d))/g, ','); }, // 格式化大数字为K、M、B等形式 formatLarge: (num: number, decimalPlaces: number = 1): string => { if (isNaN(num)) return '0'; const thresholds = [ { value: 1, symbol: '' }, { value: 1000, symbol: 'K' }, { value: 1000000, symbol: 'M' }, { value: 1000000000, symbol: 'B' }, { value: 1000000000000, symbol: 'T' } ]; // 找到合适的阈值 const threshold = thresholds .reverse() .find(threshold => num >= threshold.value); if (!threshold) return '0'; // 计算并格式化 const result = num / threshold.value; return `${result.toFixed(decimalPlaces)}${threshold.symbol}`; }, // 格式化数字为中文形式(万、亿等) formatChinese: (num: number, decimalPlaces: number = 1): string => { if (isNaN(num)) return '0'; const thresholds = [ { value: 1, symbol: '' }, { value: 10000, symbol: '万' }, { value: 100000000, symbol: '亿' } ]; // 找到合适的阈值 const threshold = thresholds .reverse() .find(threshold => num >= threshold.value); if (!threshold) return '0'; // 计算并格式化 const result = num / threshold.value; return `${result.toFixed(decimalPlaces)}${threshold.symbol}`; } };