The Best Way to Calculate a Total Sum with Comma-Separated Values in AngularJS

In my application, I am utilizing the MEAN stack with AngularJS as the front-end. I am trying to figure out how to calculate the total sum and include comma values. I have managed to get the total sum value, but the comma value is not being calculated properly. You can take a look at my Plunker for more details. For example, when I calculate the total sum of "amt" values without commas, I get the answer 3850.20. But when I include the commas in the "amount payment" values, the total sum I get is 2.00. I am expecting a result like 3850.20. If anyone knows the solution, I would appreciate your help. 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"
},

For reference, I have created a Plunker: Plunker

Answer №1

It is advisable to avoid storing or passing numbers with formatting included. For example, instead of passing the number "amount_payment": "1,925.10", it is better to pass it as "amount_payment": "1925.10" (without comma) or even better as a float: "amount_payment": 1925.10. You can then format it in your views using the Number's toLocaleString() function like this: (1925.10).toLocaleString() or ("1925.10").toLocaleString(). When summing up the values, you can simply remove commas:

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

You can also utilize the reduce() function for summing up:

app.filter('sumOfValue', function() {
  return function(data, key) {
    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);
  }
})

Here is a link to a plunker example: http://plnkr.co/edit/8Hllaw254sBO2nbaZlKQ?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is a server necessary for utilizing HTML5's WebSockets?

Do I need to write server code when implementing WebSockets? Specifically, does the JavaScript in my client application have to connect to a dedicated server, or can my current Apache server handle this functionality? ...

Method for eliminating double quotes from a string bound in Angular

https://i.sstatic.net/fWF8M.png https://i.sstatic.net/fWF8M.png Check out this code snippet: var app = angular.module('umovie-app'); app.directive('renamable', function($sce) { return { scope: { model: '=model', ...

Ways to restrict the input of only a single value when writing data using Firebase security guidelines

I'm feeling a little lost when it comes to understanding Firebase security rules - specifically about the concept of working from the top-down according to the documentation. Here is the rule that's causing me some confusion: "rules": { " ...

Tips for preventing an element from scrolling horizontally along with the page body

This is the structure of my HTML: <div class='header-wrapper'> <div class='title'>Title</div> </div> <div class='some-wide-content'> </div> Let's imagine a scenario where the br ...

"How can I adjust the height of a Bootstrap column to match the height of its neighboring column

In my Bootstrap 4 layout, I have set up two columns... The left column contains three cards in columns The right column has a list group The content in the list group is longer than that of the cards on the left side. Is there a way to make the height ...

What is the best way to centralize the storage of my website's header and footer?

Constantly updating headers and footers requires me to manually transfer the code to each web page every time, which is not the most efficient method. I'm considering using a "header" and "footer" div, and using jQuery's $(document).ready functio ...

``There seems to be a problem with the module execution

Currently, I am working on an AngularJS application where I need to ensure that the app only boots up once all data is fully loaded. To achieve this, I am trying to make requests in JSONP format and loading the $resource module using a .run statement. Bel ...

How to Exclude ress.css in Vuetify.js

How can I prevent ress.css from conflicting with Bootstrap and my custom styles in Vuetify? I attempted to remove it from the Vuetify directory within node_modules, but that did not resolve the issue. ...

Position the image between two div containers in the center of the screen, ensuring it is responsive and does not overlap with any text

I've been working on trying to position an image between two divs on my webpage. So far, I've managed to place the image there but it's not responsive (only displays correctly at a width of 1920) and ends up overlapping the text in both divs ...

Create a feature that allows users to dynamically add and remove image fields, with the ability to insert the selected images into a database

I'm currently using the following code and I am able to add attachments, but I'm facing an issue when trying to remove them. Can someone please help me with this problem? I tried adding an alert on the remove button and it seems to be working, h ...

Utilize a single CDN or multiple CDNs to access and retrieve files

When I visit a standard webpage, I usually load the following resources from various CDNs: jQuery Angular Bootstrap Icomoon several Angular plugins Would it be more efficient to load all these resources from a single CDN, or is it fine to use multiple ...

Is there a way for me to superimpose text onto an image in this instance?

I am attempting to place a "Text overlay goes here" over the profilepic.jpg image below. I believe there may be an issue with my CSS code. My approach was to create a new div class named overlay and embed that line within the imgcontainer class. Can some ...

Identify support for the :first-child pseudo-class

Is there a way to determine with JavaScript whether the browser is compatible with the CSS :first-child selector? ...

Dimensional adjustments for Semantic-ui dropdowns

Currently, we are attempting to transform bootstrap into semantic-ui. <select id="sayfaArama" class="ui search dropdown"> <option value="">Searching in pages...</option> </select> Take a look at this image I have encountered ...

PHP not compatible with Fancybox iframe

I'm facing a simple problem that I can't seem to figure out. I have a button that, when clicked, opens a fancybox with an iframe displaying a page from my website. This page includes a form for sending an email. Everything works fine except that ...

How do I create a clean HTML file when using the email editor with TinyMCE?

I was able to develop my own email editor, inspired by this particular example. To enhance user experience, I included a download button at the end of the file so that users can easily retrieve their edited content. The issue I'm facing is that tinym ...

Storing a selected database column as a variable from an HTML page in Node.js with Express

My website showcases flight information pulled from a MySQL database. The process begins with a form where users select destinations and dates for their desired flight. Once the form is submitted, users are directed to another page where flights matching t ...

changing size when hovered over with the mouse is not consistent between entering and exiting

Hi there, I'm currently utilizing the transform: scale(); property on a website and could use some assistance with a particular issue I haven't been able to find an answer for online. Here is the code snippet I'm working with: HTML: <d ...

How can I make a row div taller?

Looking at the livelink and code provided below, I have successfully created a responsive grid layout. The last adjustment that needs to be made is to change some of the squares from square shape to rectangular. The top two squares in the second column an ...

How to avoid clipping in Bootstrap 4 when a row overflows with horizontal scrolling

In order to allow for horizontal scrolling of all contained columns, I created a row using the row class. To implement this feature, I followed advice from a contributor on Stack Overflow. You can view their answer by following this link: Bootstrap 4 hori ...