Filters missing in AngularJS 1.5.x

Very quickly after beginning my adventure with AngularJS I’ve discovered that at least couple of obvious filters are missing. The list of built-in filters is here. The way to go is to add custom filters. So here are my propositions:

Percentage formatting filter

I’ve found very good implementation (because simple) on the GitHub: percent-filter.js by Jeff Johnson. I’m attaching his implementation below in a copy-and-paste ready form. BTW: this filter assumes the percentage value is given as a number such that 1 represents 100%, 0.35 represents 35%, etc.

app.filter('percentage', ['$filter', function ($filter) {
        return function (input, decimals) {
            return $filter('number')(input * 100, decimals) + '%';

Usage: {{value | percentage}} or {{value | percentage:n}} where “n” is the number of places after the decimal point.

File size formatting filter

The following filter formats given number as a file-size with automatically selected unit (bytes, kilobytes, megabytes, etc.) assuming that 1 KB = 1024 B, 1 MB = 1024 KB, etc. My implementation is an improved version of the filter found in stryju’s (tomasz stryjewski) comment (May 12, 2014) on this GitHub page. The improvement is for proper formatting of file size in bytes when the precision is given so we avoid ending with something like “0.0 B”. And I’ve added a condition so unit variable is a proper index for units array in any case.

app.filter('filesize', function () {
    var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];

    return function (bytes, precision) {
        bytes = parseFloat(bytes);
        if (isNaN(bytes) || !isFinite(bytes)) {
            return '?';

        var unit = 0;
        while (bytes >= 1024 && unit < (units.length - 1)) {
            bytes /= 1024;
        if (unit == 0) {
            precision = 0;

        return bytes.toFixed(precision) + ' ' + units[unit];

Usage: {{value | filesize}} or {{value | filesize:n}} where “n” is the number of places after the decimal point and “value” is number of bytes.

About krzysztoftomaszewski

I've got M.Sc. in software engineering. I graduated in 2005 at Institute of Computer Science, Warsaw University of Technology, Faculty of Electronics and Information Technology. I'm working on computer software design and engineering continuously since 2004.
This entry was posted in JavaScript and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s