Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active November 28, 2021 01:07
Show Gist options
  • Save james2doyle/4aba55c22f084800c199 to your computer and use it in GitHub Desktop.
Save james2doyle/4aba55c22f084800c199 to your computer and use it in GitHub Desktop.
Vue.js pretty bytes filter. This filter formats bytes into human readable formats
// 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;
});
@YuriFontella
Copy link

Thanks... Perfeito!

@AnalyzePlatypus
Copy link

Excellent.

@godolf
Copy link

godolf commented Mar 8, 2019

good job!

@bahiaxip
Copy link

bahiaxip commented Jan 6, 2021

Great!

@rehmatworks
Copy link

rehmatworks commented Aug 10, 2021

Shouldn't you divide by 1024? Thank you for the good work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment