简体   繁体   中英

How to add sum of currency values of an array in javascript

how to add currency values of an array like this

array = [ '$0',
  '$0',
  '$14,792',
  '$152,445',
  '$1,581,033',
  '$2,988,978',
  '$4,226,419',
  '$7,254,960',
  '$10,726,945',
  '$12,657,402',
  '$35,215,787',
  '$37,968,368',
  '$7,648,445',
  '$364,237',
  '$390,395',
  '$306,080',
  '$3,641,253',
  '$4,328,363',
  '$1,360,664' ]

here is my method defined, the only problem i am facing is in the second for array_sum is not adding the values that i am getting from data variable.

exports.GetMonthsFWSeasonFullSeasonValues = () => {
  var promises = [];
  var array_sum = 0;
  for(var month_index = 9; month_index <= 27 ; month_index++){
    const elm_xpath = utils.GetXpathForSubCategory(chosen_season_index, month_index);
    promises.push(element(by.xpath(elm_xpath)).getText());
  }
  return Promise.all(promises).then(function(data){
    if(data != null) {
      for (var array_index = 0; array_index < data.length; array_index++){
        array_sum += data[array_index];
        console.log('sum of values from months',array_sum);
      }
    } else {
      return null;
    }
  });
};

The problem here is that you are trying to add two strings. The + operator is overloaded in JS, so with numbers it adds them, but with strings it concatenates them. You need to convert them to ints or floats by using parseInt or parseFloat, and get rid of the commas and $ signs out of it, something like:

var num = '$1,100'
parseInt(num.replace(/[$,]/g, ''))

Which would give 1100 if you printed it. After they are in number format, you can sum them.

Or if you have the choice to store the numbers in your array as numbers, without the string formatting to start off with, go with that. So much easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM