/ JavaScript

AngularJS currencyFilter with fractionSize for AngularJS 1.2

AngularJS v1.3+ includes an optional fractionSize parameter to be passed to the filter.

In AngularJS v1.2:

<span data-ng-bind="ctrlRef.someMoney | currency: '£'"></span>

Displays:

£1,000.00

In AngularJS v1.3 and above; you are able to specify an optional fraction size:

<span data-ng-bind="ctrlRef.someMoney | currency: '£': 0"></span>

Which displays:

£1,000

In AngularJS v1.2, when you want to display the figure without the fraction it’s a little more complicated as you generally must write your own filter.

This is a bit messy, so why not just make use of the default currencyFilter by decorating it?

We’ve implement the (very basic) fractionSize functionality for the currencyFilter within our main application config method.

(function (angular) {
  angular.module('test', [])
      .config(config)
      .controller('TestController', TestController);

  function config($provide) {

      function currencyFilter($delegate, numberFilter) {

          return function (amount, currencySymbol, fractionSize) {
              // Get the existing currency filter
              var currency = $delegate.apply($delegate, arguments);
              // Format the value with our chosen fraction size
              var fraction = numberFilter(amount, fractionSize);
              // Reformat the filtered value with our fraction size
              return currency.replace(/[0-9]+.*[0-9]+/, fraction);
          };
      }
      currencyFilter.$inject = ['$delegate', 'numberFilter'];

      $provide.decorator('currencyFilter', currencyFilter);
  }
  config.$inject = ['$provide'];

  function TestController() {

      var vm = this;

      vm.testValue = 15787000.45678;
  }
})(window.angular);    

By including the above in your application config method; you are able to use the currencyFilter just how you would with AngularJS 1.3.

<span data-ng-bind="ctrlRef.someMoney | currency: '£': 0"></span>

Which displays:

£1,000

Thanks to Bart Meinders for taking our massively basic implementation and making it function more "the Angular way" by reusing the existing filters better.

It's quite an elegant implementation.

You can see this working in our jsfiddle.