Skip to content

Commit 203a83c

Browse files
committed
fix(utils): correct byte formatting boundaries for rounding
1 parent 54929ce commit 203a83c

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-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/format-bytes.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const t = require('tap')
2+
const formatBytes = require('../../../lib/utils/format-bytes.js')
3+
4+
t.test('formatBytes', (t) => {
5+
t.equal(formatBytes(0), '0 B', '0 bytes')
6+
t.equal(formatBytes(1), '1 B', '1 byte')
7+
t.equal(formatBytes(10), '10 B', '10 bytes')
8+
t.equal(formatBytes(999), '999 B', '999 bytes')
9+
t.equal(formatBytes(1000), '1.0 kB', '1000 bytes')
10+
t.equal(formatBytes(1001), '1.0 kB', '1001 bytes')
11+
t.equal(formatBytes(1500), '1.5 kB', '1500 bytes')
12+
13+
// Edge cases around rounding that currently fail
14+
t.equal(formatBytes(999999), '1.0 MB', '999999 bytes -> 1.0 MB')
15+
t.equal(formatBytes(1000000), '1.0 MB', '1000000 bytes -> 1.0 MB')
16+
17+
t.equal(formatBytes(999999999), '1.0 GB', '999999999 bytes -> 1.0 GB')
18+
t.equal(formatBytes(1000000000), '1.0 GB', '1000000000 bytes -> 1.0 GB')
19+
20+
// Checking formatting without space
21+
t.equal(formatBytes(999, false), '999B', '999B no space')
22+
t.equal(formatBytes(1000, false), '1.0kB', '1.0kB no space')
23+
24+
t.end()
25+
})

0 commit comments

Comments
 (0)