Skip to content
Source
Sign inSign up

formatBytes.ts

16 lines592 Bytes

1function formatScaled(value: number): string {
2 return value.toFixed(value >= 100 ? 0 : value >= 10 ? 1 : 2);
3}
4​
5export function formatBytes(value: number): string {
6 if (Math.round(value) < 1_024) return `${Math.round(value)} B`;
7 const units = ["KB", "MB", "GB", "TB"] as const;
8 let next = value / 1_024;
9 let unitIndex = 0;
10 // Pick the unit after rounding, so 1023.6 KB reads "1.00 MB", not "1024 KB".
11 while (Number(formatScaled(next)) >= 1_024 && unitIndex < units.length - 1) {
12 next /= 1_024;
13 unitIndex += 1;
14 }
15 return `${formatScaled(next)} ${units[unitIndex]}`;