javascript 如何在angularjs中对数字进行复数和格式化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20526897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pluralize and format a number in angularjs
提问by Benjamin Crouzier
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:
但这很失败,因为对于等于或大于 1000 的数字,它们像1,000
在count
属性中一样传递,因此只显示千位。例如:
1001 => 1
1000 => 1
2000 => 2
etc...
Try pasting 1,000
in the box number of people
of this demofor an example.
尝试粘贴1,000
在框中number of people
的这个演示的例子。
How can I format a number AND pluralize it in angular ?
如何格式化数字并将其复数为 angular ?
回答by Benjamin Crouzier
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:
您可以直接在指令的when
属性中传递您的逻辑,ng-pluralize
如下所示:
<ng-pluralize count="amount" when="{'0': 'no bitcoins',
'1': '1 bitcoin',
'other': '{{amount | number:2}} bitcoins'}">
</ng-pluralize>
工作笨蛋。
回答by Mathew Berg
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>
jsfiddlehttp://jsfiddle.net/9zmVW/
jsfiddle http://jsfiddle.net/9zmVW/
回答by kennebec
If you want a general method you can default to adding 's',
如果你想要一个通用的方法,你可以默认添加'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+'');
}
// 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