Home > Software design >  Why are these numbers not summing in a for loop using javascript?
Why are these numbers not summing in a for loop using javascript?

Time:12-21

I'm iterating over a range, extracting 2 texts (to be converted into numbers) and summing them to put the total back into the stirng later. However, although I see the numbers logged ok, the sums give me NaN as the results. Here's the code piece:

  var totalPriceToPay = 0;
  var totalCODAmount = 0;
  if (ss.getActiveSheet().getName() == sheet.getName() && row > 1) {
    for (var a = 0; a < dataRng.length; a  ) {
      if (dataRng[a][1] == true && dataRng[a][0] == 'SHIPPED' && dataRng[a][40] != 'Yes') {

        //Isolate the Price to Pay Amounts to be summed and put the total back into the string.
        const str = dataRng[a][35].toString();
        const priceToPay = str.split(",").slice(8, 9)[0] //Extracts 8th element
        totalPriceToPay  = Number(priceToPay) //Converts it into a nº and sums to the total

        const codAmount = str.split(',').slice(9, 10)[0] //Extracts the 9th element
        totalCODAmount  = Number(codAmount) //Converts it into a nº and sums to the total

        Logger.log('Type Price To Pay: '   str.split(",").slice(8, 9)[0]);
        Logger.log('Type codAmount: '   str.split(",").slice(9, 10)[0]);
        Logger.log('Total Price to Pay: '   totalPriceToPay);
        Logger.log('Total COD: '   totalCODAmount);

Here are the logs: enter image description here

Thanks.

CodePudding user response:

The Number() constructor will give NaN when the value cannot be converted to a number. When you add NaN to a number, you get NaN. To avoid the issue, use this pattern:

        totalPriceToPay  = Number(priceToPay) || 0;
        totalCODAmount  = Number(codAmount) || 0;

CodePudding user response:

The numbers have a $ before it. You need to remove it. Use String.slice:

const priceToPay = Number(str.split(",")[8].slice(1));
  • Related