Angular calculate percentage in the HTML
Asked Answered
P

6

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?

Porridge answered 1/5, 2015 at 14:53 Comment(0)
R
25

You can use the toFixed method of Number.

((myValue/totalValue)*100).toFixed(2)
Repellent answered 1/5, 2015 at 14:56 Comment(1)
This works better (At least in ease of implementation) than the percentage pipeRampageous
A
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>
Annoying answered 1/5, 2015 at 16:45 Comment(0)
R
25

You can use the toFixed method of Number.

((myValue/totalValue)*100).toFixed(2)
Repellent answered 1/5, 2015 at 14:56 Comment(1)
This works better (At least in ease of implementation) than the percentage pipeRampageous
A
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>
Arly answered 26/2, 2016 at 20:39 Comment(0)
R
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.

Rooks answered 31/7, 2017 at 18:38 Comment(0)
G
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.

Gaeta answered 7/1, 2019 at 13:14 Comment(1)
That doesn't appear available in AngularJS (which is what the tags specify).Wsan
A
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);
}
Antependium answered 1/5, 2015 at 14:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.