Oam Psy
Oam Psy

Reputation: 8661

AngularJS .00 currency filter

I have used the .00 currency filter from: AngularJS currency filter: can I remove the .00 if there are no cents in the amount?

However, how can i adapt the filter to split the value by comma's?

For example,

Instead of £456789 It should show: £456,789

Here's a plunker i made: http://plnkr.co/edit/uDFWkPAmc7PrgDwHPDho?p=preview

Filter:

app.filter('myCurrency', ['$filter', function ($filter) {


return function(input) {
    input = parseFloat(input);
    if(input % 1 === 0) {
      input = input.toFixed(0);
    }
    return '£' + input;
  };
}]);

Upvotes: 0

Views: 333

Answers (2)

Benny Bottema
Benny Bottema

Reputation: 11493

Since you can chain filters, you could use something like the _.str trim filter:

jsFiddle

<p>My value with currency trimming filter: {{ myValue | currency:'&pound;' | _.str: 'trim':['.00'] }}</p>

result:

// My value with currency trimming filter: £242,737

In case you plan to support currencies as represented in different countries and so in case there's a comma ',' instead of a dot due to currency's l18n capability, you could consider a final version that includes both:

<p>My value with currency trimming filter: {{ myValue | currency:'&pound;' | _.str: 'trim':['.00'] | _.str: 'trim':[',00'] }}</p>

Upvotes: 1

bmleite
bmleite

Reputation: 26880

Here is one way of doing it:

app.filter('myCurrency', ['$filter', function ($filter) {
  return function(input) {
    input = parseFloat(input);
    if(input % 1 === 0) {
      input = input.toFixed(0);
    }

    return '£' + (''+input).replace(/(\d)(?=(\d{3})+($|\.))/g, "$1,");
  };
}]);

Plunker

Edit

Updated filter to use a regex instead.

Upvotes: 0

Related Questions