Search code examples
javascriptif-statementgoogle-apps-scriptcomparison-operators

Cell.getValue is not comparing values correctly


I am new to google apps script, and I am running into a problem. When I am trying to compare a cell value to two integers, it works every time. On my spreadsheet, there are only a few values that fit into these constraints. Here is my code:

  function CHECK_CORRELATION() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var rangeData = sheet.getDataRange();
    var lastColumn = rangeData.getLastColumn();
    var lastRow = rangeData.getNumRows();
    var counter = 0;
    var counter2 = 0;
    var values = rangeData.getValues()
    for (var j = 2; j <= lastRow; j++){
      var cell = sheet.getRange(j, 8)
      if (cell.isBlank()) {
        continue;
      } else {
        if (0.9<=cell.getValue()<=1.1){
          Logger.log(cell.getValue());
          counter++;
        }
        counter2++;
      }
    }
    Logger.log(counter)
    Logger.log(counter2)
    if (counter>(counter2/2)) {
      return "The idea that a student will have motivation and has a part time job co-occur"
    } else {
      return "The idea that a student will have motivation and has a part time job does not co-occur"
    }
  }

This is the logger

It shows that counter is 62 and counter2 is 62, even though it shouldn't be.

Any Help would be greatly appreciated!


Solution

  • You're already going great! I just cleaned up your for loop a bit. I'm assuming your data is in the 8th column, right?

    Let me know if this solved your problem.

    function CHECK_CORRELATION() 
    {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      var lc = sheet.getLastColumn();
      var lr = sheet.getLastRow();
      var rangeData = sheet.getRange(2, 1, lr -1, lc);
      var lastColumn = rangeData.getLastColumn();
      var lastRow = rangeData.getNumRows();
      var counter = 0;
      var counter2 = 0;
      var values = rangeData.getValues();
      
      for (var j = 0; j < values.length; j++)
      {
        var row = values[j];
        var dataToCheck = row[7];
        if ((dataToCheck != "" || dataToCheck != undefined) && dataToCheck >= 0.9 && dataToCheck <= 1.1)
        {
          counter++;
          }
          else
          {
            counter2++;
          }
          
        }
      
      Logger.log(counter)
      Logger.log(counter2)
      if (counter>(counter2/2)) 
      {
        return "The idea that a student will have motivation and has a part time job co-occur"
      } 
      else 
      {
        return "The idea that a student will have motivation and has a part time job does not co-occur"
      }
    }