如何在angularjs中对数字进行复数和格式化

How to pluralize and format a number in angularjs

本文关键字:格式化 数字 angularjs      更新时间:2024-06-21

我想格式化一个数字,并用angular将其复数化。

例如(给定一定数量的比特币):

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

我尝试过的:

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

但这失败得很惨,因为对于等于或大于1000的数字,它们在count属性中作为1,000传递,因此只显示数千。例如:

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

尝试将1,000粘贴到本演示的number of people框中作为示例。


如何格式化一个数字并将其复数化?

这里不需要使用正则表达式。

您可以直接在ng-pluralize指令的when属性中传递您的逻辑,如下所示:

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

正在工作的plunker。

你能去掉逗号让它处理吗?

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

jsfiddlehttp://jsfiddle.net/9zmVW/

如果你想要一个通用的方法,你可以默认添加"s",

并用字符串传递特定的复数形式:

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