Reputation: 3068
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?
Upvotes: 14
Views: 60693
Reputation: 186
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.
Upvotes: 3
Reputation: 958
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.
Upvotes: 4
Reputation: 8038
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>
Upvotes: 7
Reputation: 136144
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);
}
Upvotes: 1
Reputation: 1199
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>
Upvotes: 29
Reputation: 191749
You can use the toFixed
method of Number
.
((myValue/totalValue)*100).toFixed(2)
Upvotes: 25