Warm tip: This article is reproduced from serverfault.com, please click

其他-如何使用Google Apps脚本计算百分比

(其他 - How to calculate percentage with Google Apps Script)

发布于 2020-11-28 00:47:45

我正在尝试使用Google Apps脚本计算2%,并将结果插入Google Doc File中,然后导出到PDF文件。

但是,脚本执行后,我得到这个里面的PDF文件:为NaN

这是计算代码:

var totalPrice= ui.prompt ('Price :');
var price1 = (totalPrice / 100) * 40;
var price2 = (totalPrice / 100) * 60;

这是在导出PDF之前在GDoc中插入值的代码:

body.replaceText ('##TOTAL_PRICE##', totalPrice.getResponseText ());
body.replaceText ('##PRICE1##', price1);
body.replaceText ('##PRICE2##', price2);

怎么了 ?

Questioner
TooNetCreation
Viewed
11
contributorpw 2020-11-28 12:00:32

totalPrice之前检查值。

看来你没有将提示字符串转换为数字。

最好的方法是从用户那里获取价值。下面的代码检查OK用户响应和有效值。

function userAction() {
  const ui = SpreadsheetApp.getUi();
  var prompt = ui.prompt('Price :');
  var responseText = prompt.getResponseText();

  if (prompt.getSelectedButton() !== ui.Button.OK || !isNumeric(responseText)) {
    ui.alert('Nothing');
    return;
  }
  var totalPrice = +responseText;

  var price1 = (totalPrice / 100) * 40;
  var price2 = (totalPrice / 100) * 60;

  console.log(price2);
}

function isNumeric(str) {
  if (typeof str != 'string') return false;
  return !isNaN(str) && !isNaN(parseFloat(str));
}