Angular calculate percentage in the html

Abhishek picture Abhishek · May 1, 2015 · Viewed 49.2k times · Source

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?

Answer

spik3s picture spik3s · May 1, 2015

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>