/** * 流量数字显示成人读的样子。连接页和仪表盘共用。 * * 1024 进制。B 一档不带小数;其余不满 100 的保留一位小数,够 100 的取整—— * 「23.4 MB」有信息量,「234.7 MB」的小数就只是噪音了。 */ const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const export function formatBytes(bytes: number): string { if (!Number.isFinite(bytes) || bytes < 0) return '0 B' let value = bytes let unit = 0 while (value >= 1024 && unit < UNITS.length - 1) { value /= 1024 unit += 1 } const digits = unit === 0 || value >= 100 ? 0 : 1 // Number() 去掉无意义的尾零:1.0 KB → 1 KB return `${String(Number(value.toFixed(digits)))} ${UNITS[unit]}` }