AngularJS filter to format file size

Wai Park Soon
NoteToPS
Published in
1 min readNov 28, 2014

Update: This filter is useful if you need “standard-compliant” formatting. That means base-1000 for SI units and base-1024 for IEC units. If you need a more conventional filter, that uses base-1024 for SI units, you can find it in the next post.

If you are dealing with files, more often than not you will need to display file sizes in human-friendly format. Here’s a quick snippet to do that easily.

angular
.module(‘myModule’, [])
.filter(‘formatByte’, function () {
‘use strict’;
return function (size, useBinary) {
var base, prefixes;
if (useBinary) {
base = 1024;
prefixes = [‘Ki’,’Mi’,’Gi’,’Ti’,’Pi’,’Ei’,’Zi’,’Yi’];
}
else {
base = 1000;
prefixes = [‘k’,’M’,’G’,’T’,’P’,’E’,’Z’,’Y’];
}
var exp = Math.log(size) / Math.log(base) | 0;
return (size / Math.pow(base, exp)).toFixed(1) + ‘ ‘ +
((exp > 0) ? prefixes[exp — 1] + ‘B’ : ‘Bytes’);
};
});

formatByte filter expects input in the unit of bytes. It also accepts a boolean parameter to switch between SI and IEC prefixes. The default is SI prefixes since it is better accepted currently.

Hope it helps.

--

--