Skip to content

Commit 1758072

Browse files
MarcoDotIOclaudemaria-rcks
authored
fix(web): byte sizes just under the next unit no longer read "1024 KB" (#26067)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent e428a2c commit 1758072

2 files changed

Lines changed: 37 additions & 6 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { formatBytes } from "./formatBytes";
4+
5+
describe("formatBytes", () => {
6+
it.each([
7+
[0, "0 B"],
8+
[1_023, "1023 B"],
9+
[1_024, "1.00 KB"],
10+
[1_536, "1.50 KB"],
11+
[1_047_552, "1023 KB"],
12+
[1_048_576, "1.00 MB"],
13+
[5 * 1_024 ** 4, "5.00 TB"],
14+
[2_048 * 1_024 ** 4, "2048 TB"],
15+
])("formats %d bytes as %s", (value, label) => {
16+
expect(formatBytes(value)).toBe(label);
17+
});
18+
19+
it.each([
20+
[1_023.6, "1.00 KB"],
21+
[1_048_100, "1.00 MB"],
22+
[1_073_217_536, "1.00 GB"],
23+
])("moves %d bytes to the next unit when rounding reaches 1024", (value, label) => {
24+
expect(formatBytes(value)).toBe(label);
25+
});
26+
});

‎apps/web/src/lib/formatBytes.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
1+
function formatScaled(value: number): string {
2+
return value.toFixed(value >= 100 ? 0 : value >= 10 ? 1 : 2);
3+
}
4+
15
export function formatBytes(value: number): string {
2-
if (value < 1_024) return `${Math.round(value)} B`;
6+
if (Math.round(value) < 1_024) return `${Math.round(value)} B`;
37
const units = ["KB", "MB", "GB", "TB"] as const;
4-
let next = value;
5-
let unitIndex = -1;
6-
do {
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) {
712
next /= 1_024;
813
unitIndex += 1;
9-
} while (next >= 1_024 && unitIndex < units.length - 1);
10-
return `${next.toFixed(next >= 100 ? 0 : next >= 10 ? 1 : 2)} ${units[unitIndex]}`;
14+
}
15+
return `${formatScaled(next)} ${units[unitIndex]}`;
1116
}

0 commit comments

Comments
 (0)