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

How to calculate percentage with Google Apps Script

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

I'm trying to calculate 2 percentage with Google Apps Script and insert the result inside Google Doc File, and then exported to PDF file.

But after script execution I get this inside PDF file : NaN

here is the calculation code :

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

here is the code where values are inserted in GDoc before PDF export :

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

What's wrong ?

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

Check the totalPrice value before.

It seems you're not converting prompt strings to number.

The best way for this it's to get values from the user. The code below check OK user response and a valid value.

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));
}