Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 222
Benjamin Crouzier Avatar asked Dec 11 '13 18:12

Benjamin Crouzier


2 Answers

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.

like image 143
Benjamin Crouzier Avatar answered Sep 24 '22 17:09

Benjamin Crouzier


Can you just remove the commas and let it handle it?

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

jsfiddle http://jsfiddle.net/9zmVW/

like image 35
Mathew Berg Avatar answered Sep 24 '22 17:09

Mathew Berg