问题
Angular noob here! I am trying to display a percentage value in my html as follows:
<td> {{ ((myvalue/totalvalue)*100) }}%</td>
It works but sometimes it gives a very long decimal which looks weird. How do i round it off to 2 digits after the decimal? Is there a better approach to this?
回答1:
You can use the toFixed method of Number
.
((myValue/totalValue)*100).toFixed(2)
回答2:
You could use a filter, like this one below by jeffjohnson9046
The filter makes the assumption that the input will be in decimal form (i.e. 17% is 0.17).
myApp.filter('percentage', ['$filter', function ($filter) {
return function (input, decimals) {
return $filter('number')(input * 100, decimals) + '%';
};
}]);
Usage:
<tr ng-repeat="i in items">
<td>{{i.statistic | percentage:2}}</td>
</tr>
回答3:
I often use the built-in 'number' filter for that purpose;
<span>{{myPercentage | number}}</span>
For 2 decimals:
<span>{{myPercentage | number:2}}</span>
For 0 decimal;
<span>{{myPercentage | number:0}}</span>
回答4:
Use ng-bind that would not show curly braces until the expression resolved.
Html
<td ng-bind="roundedPercentage(myValue, totalValue) + '%'"></td>
Controller
$scope.roundedPercentage = function(myValue, totalValue){
var result = ((myValue/totalValue)*100)
return Math.round(result, 2);
}
回答5:
You could use angular percent pipe for this.
Simplest solution in a single line within html using angular would be as follows :
<td> {{ myvalue/totalvalue | percent:'2.0-2' }}</td>
if myvalue = 4 & totalvalue = 10, then result will be displayed as
40.00%
for respective html element.
回答6:
Inside your controller.js (angular.js 1.x) or app.component.ts (angular2) calculate a percentage (logic) of a total value with a another value like this.
this.percentage = Math.floor(this.myValue / this.value * 100);
Then show the percentage in the html.
<p>{{percentage}}%</p>
Simple Math Example: 3/10*100 = 30%. If myValue
is 3 and value
is 10 your result will be 30. Use Javascript's built in Math.floor()
function to round the number and remove the decimal.
来源:https://stackoverflow.com/questions/29989200/angular-calculate-percentage-in-the-html