Skip to content

Instantly share code, notes, and snippets.

@httpJunkie
Created November 30, 2015 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save httpJunkie/ce3f4bd4b8c61d9e2d2b to your computer and use it in GitHub Desktop.
Save httpJunkie/ce3f4bd4b8c61d9e2d2b to your computer and use it in GitHub Desktop.
Angular filter for formatting bytes
app.filter('bytes', function(){
return function(bytes, precision){
if (typeof bytes !== 'number') {
bytes = parseFloat(bytes);
}
if (bytes === 0) {
return '0 B';
} else if (isNaN(bytes) || !isFinite(bytes)) {
return '-';
}
var isNegative = bytes < 0;
if (isNegative) {
bytes = -bytes;
}
if (typeof precision !== 'number') {
precision = parseFloat(precision);
}
if (isNaN(precision) || !isFinite(precision)) {
precision = 1;
}
var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
var number = (bytes / Math.pow(1024, Math.floor(exponent))).toFixed(precision);
return (isNegative ? '-' : '') + number + ' ' + units[exponent];
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment