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

formatBytes.ts

41 lines1.4 KB

1import { getFormattingLocale } from "../i18n/runtime";
2​
3const formats = new Map<string, Intl.NumberFormat>();
4​
5function formatFixed(value: number, digits: number): string {
6 const locale = getFormattingLocale();
7 const key = `${locale}:${digits}`;
8 let format = formats.get(key);
9 if (!format) {
10 format = new Intl.NumberFormat(locale, {
11 minimumFractionDigits: digits,
12 maximumFractionDigits: digits,
13 useGrouping: false,
14 });
15 formats.set(key, format);
16 }
17 return format.format(value);
19​
20function roundScaled(value: number): { readonly rounded: number; readonly digits: number } {
21 const twoDecimals = Number(value.toFixed(2));
22 if (twoDecimals < 10) return { rounded: twoDecimals, digits: 2 };
23 const oneDecimal = Number(value.toFixed(1));
24 if (oneDecimal < 100) return { rounded: oneDecimal, digits: 1 };
25 return { rounded: Number(value.toFixed(0)), digits: 0 };
27​
28export function formatBytes(value: number): string {
29 if (Math.round(value) < 1_024) return `${Math.round(value)} B`;
30 const units = ["KB", "MB", "GB", "TB"] as const;
31 let next = value / 1_024;
32 let unitIndex = 0;
33 let scaled = roundScaled(next);
34 // Pick the unit after rounding, so 1023.6 KB reads "1.00 MB", not "1024 KB".
35 while (scaled.rounded >= 1_024 && unitIndex < units.length - 1) {
36 next /= 1_024;
37 unitIndex += 1;
38 scaled = roundScaled(next);
39 }
40 return `${formatFixed(scaled.rounded, scaled.digits)} ${units[unitIndex]}`;