-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
30 lines (24 loc) · 806 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
module.exports = prettierBytes
function prettierBytes (num) {
if (typeof num !== 'number' || isNaN(num)) {
throw new TypeError('Expected a number, got ' + typeof num)
}
var neg = num < 0
var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
if (neg) {
num = -num
}
if (num < 1) {
return (neg ? '-' : '') + num + ' B'
}
var exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1)
num = Number(num / Math.pow(1000, exponent))
var unit = units[exponent]
if (num >= 10 || num % 1 === 0) {
// Do not show decimals when the number is two-digit, or if the number has no
// decimal component.
return (neg ? '-' : '') + num.toFixed(0) + ' ' + unit
} else {
return (neg ? '-' : '') + num.toFixed(1) + ' ' + unit
}
}