Skip to content

Commit f2c3af7

Browse files
authored
fix: more intuitive byte formatting boundaries for rounding (#8840)
## WHY/WHAT Fixed non-intuitive unit rounding for byte formatting. Previously, values close to a unit boundary (e.g. 999,999 B) displayed incorrectly as the smaller unit. We adjusted the conversion threshold (e.g. to 999,950 B for MB) to leverage standard `toFixed(1)` rounding, ensuring values that are `almost 1.0` of the next unit are correctly displayed as 1.0 MB, prioritizing a better user experience.
1 parent 6d1db87 commit f2c3af7

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

lib/utils/format-bytes.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@ const formatBytes = (bytes, space = true) => {
1313
return `${bytes}${spacer}B`
1414
}
1515

16-
if (bytes < 1000000) {
16+
if (bytes < 999950) {
1717
// kB
1818
return `${(bytes / 1000).toFixed(1)}${spacer}kB`
1919
}
2020

21-
if (bytes < 1000000000) {
21+
if (bytes < 999950000) {
2222
// MB
2323
return `${(bytes / 1000000).toFixed(1)}${spacer}MB`
2424
}

test/lib/utils/tar.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,3 +225,37 @@ t.test('should getContents of a tarball with a node_modules directory included',
225225
}, 'contents are correct')
226226
t.end()
227227
})
228+
229+
t.test('should log byte sizes correctly', async (t) => {
230+
const cases = [
231+
[0, '0 B', '0B'],
232+
[1, '1 B', '1B'],
233+
[10, '10 B', '10B'],
234+
[999, '999 B', '999B'],
235+
[1000, '1.0 kB', '1.0kB'],
236+
[1001, '1.0 kB', '1.0kB'],
237+
[1500, '1.5 kB', '1.5kB'],
238+
[999999, '1.0 MB', '1.0MB'],
239+
[1000000, '1.0 MB', '1.0MB'],
240+
[999999999, '1.0 GB', '1.0GB'],
241+
[1000000000, '1.0 GB', '1.0GB'],
242+
]
243+
244+
for (const [size, expected, expectedNoSpace] of cases) {
245+
const logs = printLogs({
246+
name: 'pkg',
247+
version: '1.0.0',
248+
files: [
249+
{ path: 'file.txt', size: size },
250+
],
251+
bundled: [],
252+
size: size,
253+
unpackedSize: size,
254+
integrity: 'sha512-xxx',
255+
})
256+
257+
t.match(logs, `package size: ${expected}`, `package size: ${expected}`)
258+
t.match(logs, `unpacked size: ${expected}`, `unpacked size: ${expected}`)
259+
t.match(logs, `${expectedNoSpace} file.txt`, `file size: ${expectedNoSpace}`)
260+
}
261+
})

0 commit comments

Comments
 (0)