Search code examples
htmlcssangularjsmeanjs

How To Total Sum Along With Comma Values in Angularjs?


I am using MEAN stack in my application with AngularJS as my front-end. How to total sum along with comma value , actually I got the total sum value but the comma value is not calculated...My Plunker For Example :- without comma amt values total sum answer I got 3850.20, then with comma of amount payment values total sum I got 2.00, Expecting like 3850.20 , If any one knows the solution help to us thanks....

My controller:-

    .filter('sumOfValue', function () {
    return function (data, key) {
        debugger;
        if (angular.isUndefined(data) && angular.isUndefined(key))
            return 0;        
        var sum = 0;

        angular.forEach(data,function(v,k){
            sum = sum + parseFloat(v[key]);
        });        
        return sum.toFixed(2);
    }
})

My Html:-

<td >{{mani.amt}}</td>

  <td >{{mani.amount_payment }}</td>

My Data:-

    {
"_id": "5816f4fad0be79f809519f98",
"user": {
"_id": "57400c32bd07906c1308e2cf",
"displayName": "mani selvam"
},
"__v": 0,
"created": "2016-10-31T07:38:34.999Z",
"remarks": "-",
"status": "pending",
"amt": "1925.10",
"cheque_currency": "Rs",
"cheque_value": "300",
"amount_payment": "1,925.10",
"debitnote_no_payment": "3",
"supplier_name": "karikalan",
"buyer_name": "Manidesigns"
},

{
"_id": "5816f4fad0be79f809519f98",
"user": {
"_id": "57400c32bd07906c1308e2cf",
"displayName": "mani selvam"
},
"__v": 0,
"created": "2016-10-31T07:38:34.999Z",
"remarks": "-",
"status": "pending",
"amt": "1925.10",
"cheque_currency": "Rs",
"cheque_value": "300",
"amount_payment": "1,925.10",
"debitnote_no_payment": "3",
"supplier_name": "karikalan",
"buyer_name": "Manidesigns"
},

I have created Plunker for reference:- Plunker


Solution

  • I think you should avoid storing/passing numbers after being formatted, so you should pass number "amount_payment": "1,925.10" as "amount_payment": "1925.10" (without comma), or even better as float: "amount_payment": 1925.10, on your views you can then format it with Number's toLocalString() function: (1925.10).toLocaleString() or even ("1925.10").toLocaleString(). In your case you can just remove commas when summing:

    angular.forEach(data,function(v){
      sum = sum + parseFloat(v[key].replace(',', ''));
    }); 
    

    also you can use reduce() function to sum:

    app.filter('sumOfValue', function () {
      return function (data, key) {
        // debugger;
        if (!data || !data[0] || !data[0][key]) {
          return 0; 
        }
    
        var sum = data.reduce(function(sum, val) {
          return sum + parseFloat(val[key].replace(',', ''));
        }, 0);
    
        return sum.toFixed(2);
      }
    })
    

    plunker: http://plnkr.co/edit/8Hllaw254sBO2nbaZlKQ?p=preview