Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

formatBytes.ts

20 lines737 Bytes

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