Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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/

If you want a general method you can default to adding 's',

and pass specific plural forms with the string:

function plural(s, pl){
    var n= parseFloat(s);
    if(isNaN(n) || Math.abs(n)=== 1) return s;
    if(!pl) return s+'s';
    return s.replace(/\S+(\s*)$/, pl+'$1');
}

// test:
[0, .5, 1, 1.5, 2].map(function(itm){
    return [plural(itm+' bitcoin'), 
    plural(itm+' box', 'boxes'), 
    plural(itm+' foot', 'feet')];
}).join('\n');


// returned values:
0 bitcoins, 0 boxes, 0 feet
0.5 bitcoins, 0.5 boxes, 0.5 feet
1 bitcoin, 1 box, 1 foot
1.5 bitcoins, 1.5 boxes, 1.5 feet
2 bitcoins, 2 boxes, 2 feet
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top