14

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?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Abhishek
  • 2,998
  • 9
  • 42
  • 93

6 Answers6

29

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>
spik3s
  • 1,189
  • 2
  • 11
  • 27
24

You can use the toFixed method of Number.

((myValue/totalValue)*100).toFixed(2)
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
7

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>
Andrew
  • 7,848
  • 1
  • 26
  • 24
4

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.

Ian Poston Framer
  • 938
  • 12
  • 16
3

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71
1

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);
}
Venu
  • 7,243
  • 4
  • 39
  • 54
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299