0

I use this code to subtract one column from another but the cell with 0 remains the same . When there is 0 in a cell and another is 6 after subtraction it should be -6 but this code does not perform subtraction when there comes 0. How to remove this problem

function subtractSoldBulk() {
var sheet = SpreadsheetApp.getActiveSheet();
var maxRows = sheet.getMaxRows();

var soldRange = sheet.getRange(2, 3, maxRows); // 
row, column, number of rows
var totalRange = sheet.getRange(2, 4, maxRows);

var soldValues = soldRange.getValues();
var totalValues = totalRange.getValues();
for (var row in soldValues) {
var soldCellData = soldValues[row][0];
var totalCellData = totalValues[row][0];

if (soldCellData != "" && totalCellData != "") {
  totalValues[row][0] = totalCellData - 
soldCellData;
  soldValues[row][0] = "";
}
}

soldRange.setValues(soldValues);
totalRange.setValues(totalValues);
}
Rubén
  • 34,714
  • 9
  • 70
  • 166
Negativeplus
  • 5
  • 1
  • 4

1 Answers1

3

JavaScript is a weird language. Look at what the expression below evaluates to and things should become clear:

enter image description here

Remember that JS engine will attempt to convert both operands to a single type (in this case, a number). The numerical value of an empty string is '0', so your 'if' statement expression will evaluate to 'false'. To avoid this situation, use strict comparison '!=='.

Anton Dementiev
  • 5,451
  • 4
  • 20
  • 32