Summing Negative Items in Related List View

Hello,

I have a SharePoint form with a List object on it that allows users to add related items and their cost. Using code I found in a previous post on here(thanks!), I was able to satisfy a business requirement to sum the cost of each item in the list view and enter that value into a field on the form. This was working great, until today when I was told by the business that some items would have negative values. In it's current state if someone enters one item for $1000 and another for -$1000 the total field shows $2000 instead of $0. I tried adding my own logic to subtract if the value was negative, but that doesn't seem to be work.

for (var i = 0; i < items.length; i++){

 valueTC = parseFloat(items[i].FCRTotalCost.replace(/[^0-9.]/g, ""));
            
     if (Math.sign(valueTC) > 0) {
         totalTC += valueTC;
     } else {
         totalTC -= valueTC;
     }
}

I'm assuming it has something to do with the parseFloat line since when I step through it in the browser debugger the item shows a value of ($1000) but valueTC evaluates to 1000.

Any help would be appreciated! Thanks!

Matt

Hello @mkorek,

You can try out using another Regex expression. like this:

parseFloat(items[i].FCRTotalCost.replace(/[^0-9.-]+/g, '')

Hi @mnikitina ,

Thank you for the response!

I've tried updating my code to use your Regex expression, but negative numbers are still coming through as positive. So if I have one item where FCRTotalCost is 1000 and another item where FCRTotalCost is -1000, it's still evaluating to 2000 instead of 0.

Matt

@mkorek,

I suppose that you've updated just the Regex expression. As negative numbers are working now, you need to remove this part of the code:

     if (Math.sign(valueTC) > 0) {
         totalTC += valueTC;
     } else {
         totalTC -= valueTC;
     }

The final code should be this:

for (var i = 0; i < items.length; i++){

 totalTC += parseFloat(items[i].FCRTotalCost.replace(/[^0-9.-]+/g, ''));

}

@mnikitina,

Sorry, I probably didn't make this very clear in my response. The negative numbers are still evaluating to positive after updating the Regex expression.

Thank you for the response,

Matt

@mkorek,

Thank you for the screenshot, that makes sense now.

You need to get this value:
image

And you won't need to remove any special signs.

for (var i = 0; i < items.length; i++){

 totalTC += parseFloat(items[i]['FCRTotalCost.']);

}

@mnikitina,

That worked perfectly! Thank you!!!

1 Like