Benjamin Crouzier Benjamin Crouzier - 1 year ago 77
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'}">

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

1001 => 1
1000 => 1
2000 => 2

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

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

Answer Source

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'}">

Working plunker.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download