Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Divide a Variable by a Number in Apps Script

I am trying to divide a JSON response by a number.

Here’s my code:

 function readData() {

var accesstoken = "TOKEN"

 var sheet = SpreadsheetApp.getActiveSheet()
    
 var campaignstatsurl = "https://adsapi.snapchat.com/v1/campaigns/e431cbcd-2281-49fe-8d05-b26c87660eb5/stats?&granularity=TOTAL&fields=impressions,swipes,video_views,view_completion,spend,video_views_time_based"

 var campaignstatsurlresponse = UrlFetchApp.fetch(campaignstatsurl, {
       headers: {
           "Authorization": "Bearer " + accesstoken
       }
   });  

var campaignstatsdata = JSON.parse(campaignstatsurlresponse.getContentText());


var spendvalues = campaignstatsdata.total_stats.map(({ total_stat: { stats } }) => [stats.spend])
sheet.getRange(3, 6, values.length).setValues(spendvalues);

}

I am trying to divide the

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 var spendvalues 

By 1,000,000

I have tried the below:

sheet.getRange(3, 6, values.length).setValues(spendvalues/1000000);

I get the following error:

 Exception: The parameters (number) don't match the method signature for SpreadsheetApp.Range.setValues.

Thank you for your help.

>Solution :

From your following reply,

In my code, the output for "sheet.getRange(3, 6, values.length).setValues(spendvalues)" on Google Sheet is "13333330000". I would like to divide that number, by 1,000,000. So I want the output on Google Sheets to be "13,333.33" instead of "13333330000"

I guessed that your value of spendvalues might be a 2-dimensional array like [[123], [456],,,]. If my understanding is correct, I’m worried that this might be the reason for your current issue. So, how about the following modification?

From:

sheet.getRange(3, 6, values.length).setValues(spendvalues);

To:

sheet.getRange(3, 6, spendvalues.length).setValues(spendvalues.map(([e]) => [Number(e) / 1000000])); // or [e / 1000000]

Reference:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading