Benjamin Crouzier Benjamin Crouzier - 26 days ago 8
AngularJS Question

How to pluralize and format a number in angularjs

I want to do format a number and pluralize it with angular.

For example (given a number of bitcoins):

0 => "John has no bitcoins"
1 => "John has 1 bitcoin"
2 => "John has 2 bitcoins"
12345.6789 => "John has 12,345.67 bitcoins"


What I've tried:

John has
<ng-pluralize count="bitcoin_amount | round:2"
when="{'0': 'no bitcoins',
'1': '1 bitcoin',
'other': '{} bitcoins'}">
</ng-pluralize>


But this fails miserably, because for numbers equal or bigger than 1000, they are passed as
1,000
in the
count
attribute, so only thousands are shown.
Eg:

1001 => 1
1000 => 1
2000 => 2
etc...


Try pasting
1,000
in the box
number of people
of this demo for an example.




How can I format a number AND pluralize it in angular ?

Answer

There is no need to use a regular expresssion here.

You can pass your logic directly in the when attribute of the ng-pluralize directive like so:

<ng-pluralize count="amount" when="{'0': 'no bitcoins', 
                     '1': '1 bitcoin', 
                     'other': '{{amount | number:2}} bitcoins'}">
</ng-pluralize>

Working plunker.