Created
November 30, 2015 04:00
-
-
Save httpJunkie/ce3f4bd4b8c61d9e2d2b to your computer and use it in GitHub Desktop.
Angular filter for formatting bytes
This file contains 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
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