If var isnumber, for script

南笙酒味 提交于 2019-12-04 01:47:22
Ed Nelson

This will check if A1 is a number:

function ifIsNumber() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = ss.getActiveSheet();
    var substring1 = s.getRange("A1").getValue();
    if (!isNaN(parseFloat(substring1)) && isFinite(substring1)) {
        s.getRange("B1").setValue("Is a number");
    } else {
        s.getRange("B1").setValue("Not a number");
    }
}

Google Apps Script could use most of the JavaScript methods and operators.

One alternative to check if an object is a number is to use typeof.

The following code will return the type of the value of the cell specified by the reference.

function typeofcellvalue(reference) {
  var ss = SpreadsheetApp.getActive();
  var rng = ss.getRange(reference);
  var value = rng.getValue();
  return typeof value;
}

Example of use as a custom function

=typeofcellvalue("A1")

If cell A1

  • has a number, the result will be number.
  • is empty, the result will be string.

If you want to do number stuff if the value is a number or a string representation of a number you can do the following:

if (!isNaN(myVar)){//myVar is either a number or a string representing a number
    myNumericVar = +myVar;//convert myVar to number if necessary
    //do number stuff
} else {
   //do non-numeric stuff
}

See:

(Built-in) way in JavaScript to check if a string is a valid number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!