【问题标题】:Angular calculate percentage in the html角度计算html中的百分比
【发布时间】:2015-07-11 10:08:48
【问题描述】:
这里有角菜鸟!我试图在我的 html 中显示一个百分比值,如下所示:
<td> {{ ((myvalue/totalvalue)*100) }}%</td>
它可以工作,但有时它会给出一个很长的小数,看起来很奇怪。如何将其四舍五入到小数点后两位?有更好的方法吗?
【问题讨论】:
标签:
javascript
angularjs
number-formatting
angularjs-interpolate
【解决方案1】:
您可以使用过滤器,例如下面jeffjohnson9046 的过滤器
过滤器假设输入为十进制形式(即 17% 为 0.17)。
myApp.filter('percentage', ['$filter', function ($filter) {
return function (input, decimals) {
return $filter('number')(input * 100, decimals) + '%';
};
}]);
用法:
<tr ng-repeat="i in items">
<td>{{i.statistic | percentage:2}}</td>
</tr>
【解决方案2】:
可以使用Number的toFixed方法。
((myValue/totalValue)*100).toFixed(2)
【解决方案3】:
为此我经常使用the built-in 'number' filter;
<span>{{myPercentage | number}}</span>
两位小数:
<span>{{myPercentage | number:2}}</span>
对于 0 小数;
<span>{{myPercentage | number:0}}</span>
【解决方案4】:
在你的 controller.js (angular.js 1.x) 或 app.component.ts (angular2) 中计算总值的百分比(逻辑)和这样的另一个值。
this.percentage = Math.floor(this.myValue / this.value * 100);
然后在html中显示百分比。
<p>{{percentage}}%</p>
简单数学示例:3/10*100 = 30%。如果myValue 是3,value 是10,那么你的结果就是30。使用Javascript 内置的Math.floor() 函数来舍入数字并去掉小数点。
【解决方案5】:
您可以为此使用角度 percent 管道。
在 html 中使用 angular 的单行中最简单的解决方案如下:
<td> {{ myvalue/totalvalue | percent:'2.0-2' }}</td>
如果 myvalue = 4 & totalvalue = 10,则结果显示为
40.00%
用于相应的 html 元素。
【解决方案6】:
使用在表达式解析之前不会显示花括号的 ng-bind。
HTML
<td ng-bind="roundedPercentage(myValue, totalValue) + '%'"></td>
控制器
$scope.roundedPercentage = function(myValue, totalValue){
var result = ((myValue/totalValue)*100)
return Math.round(result, 2);
}