Forked from james2doyle/vue.pretty-bytes.filter.js
Last active
January 10, 2019 17:18
-
-
Save iknowmagic/96d4be25f3829a2e9ce746525527215c to your computer and use it in GitHub Desktop.
Vue.js pretty bytes filter. This filter formats bytes into human readable formats
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// usage: {{ file.size | prettyBytes }} | |
Vue.filter('prettyBytes', function (num) { | |
// jacked from: https://github.com/sindresorhus/pretty-bytes | |
if (typeof num !== 'number' || isNaN(num)) { | |
throw new TypeError('Expected a number'); | |
} | |
var exponent; | |
var unit; | |
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'; | |
} | |
exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1); | |
num = (num / Math.pow(1000, exponent)).toFixed(2) * 1; | |
unit = units[exponent]; | |
return (neg ? '-' : '') + num + ' ' + unit; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment