String number to fixed Integer Google script - javascript

I am having trouble to convert a string 'u12345678910' to an integer without scientific notation. So basically, it literally needs to be exactly 12345678910.
How I have approached it:
1. slice the 'u' to get the number i want (after slice its still a string) OR use .replace()
2. tried parseInt(), Number(), both give me a number in scientific notation.
3. parseFloat() & then parseInt(), don't know why but read somewhere that this might work, it didn't.
Why do i need this exact number?
Since it is a chartId of an EmbeddedChart & Google Slides API is giving me the error that the ID needs to be of TYPE_INT32.
Hopefully someone has a solution to this, since its the only thing blocking my project at the moment :(
Please find below some sample code of how to reproduce.
*I am working in Google Apps Script, Chart is in Spreadsheet & I am using the Google Slides API library of Spencer Easton
var ss = SpreadsheetApp.getActiveSpreadsheet(),
allSheets = ss.getSheets();
var chart = allSheets[0].getCharts()[0],
chartId = chart.getId(); // this returns 'u12345678910'
var chartStringNumber = chartId.slice(1); // returns 12345678910 (string)
var chartIdNumber = Number(chartStringNumber); // Here I want the result to be typeof INT & 12345678910, but i keep getting a number incl scientific notation. I have also tried parseInt().

The chartID returned by the built-in SpreadsheetApp service is a string value that can be overridden using setId(), and starts as an arbitrary value - so it's not the id you want.
To use the Slides API you need the 'real' chart ID which is available from the Advanced Spreadsheet Service, or the directly from the Sheets API.
You can use this code to enumerate the sheets and their charts & real ids using the Advanced Service.
var ch = Sheets.Spreadsheets.get(ss.getId(), {
"fields": "sheets(charts/chartId,properties(sheetId,title))"
});
var sheets = ch.sheets.map (function (d) {
return {
id:d.properties.sheetId,
name:d.properties.title,
charts:d.charts
}
});

Related

How to parseInt or ParseInt embedded data with TypeScript in Qualtrics?

Even when I save an integer to embedded data earlier in the survey flow (in previous blocks on different screens), I am not able in Javascript to get the embedded data value, ensure it is parsed as a number/integer, then use it in a loop. Is this something about TypeScript? I didn't see anything about parseInt or ParseInt in the TypeScript documentation.
For example, suppose I do the following:
// Draw a random number
var x = Math.floor(Math.random() * 5);
// Save it in embedded data
Qualtrics.SurveyEngine.setEmbeddedData("foo", x);
// In a later block on a different screen, get the embedded data as an integer
var x_new = "${e://Field/foo}"; // not an int
var x_new = parseInt("${e://Field/foo}"); // doesn't work
var x_new = ParseInt("${e://Field/foo}"); // doesn't work
// Loop using x_new:
for(i = 0; i < x_new; i++) {
console.log(i)
}
Any idea why this isn't working? Perhaps I just don't know how to parseint().
In "normal" JS runtime system, we have parseInt function, the function gets a string (like number string) as a parameter. In this env, we don't support your syntax - "${e://Field/foo}", because it is not a "number string".
In Qualtrics system environment they have parseInt too, but they support their custom syntax "${e://Field/foo}" to get EmbeddedData.
Make sure that your code is running on Qualtrics system environment.
ParseInt is just turning your string into an integer.
Look at the demo below.
let myVar = "${e://Field/foo}"; // This is a string
console.log(myVar); // This prints a string
console.log(parseInt(myVar)); // This prints "NaN", i.e. Not a Number, because the string isn't a representation of a number.

Automatically replace dots with commas in a Google Sheets Column with Google Script

I have a WooCommerce store, which is connected with Zapier to a Google spreadsheet. In this file, I keep track of the sales etc. Some of these columns contain -obviously- prices, such as price ex VAT, etc. However, for some reason the pricing values are stored in my spreadsheet as strings, such as 18.21.
To be able to automatically calculate with these values, I need to convert values in these specific columns to numbers with a comma as divider. I'm new to Google Script, but with reading some other post etc, I managed to "write" the following script, which almost does the job:
function stringIntoNumber() {
var sheetActive = SpreadsheetApp.openById("SOME_ID");
var sheet = sheetActive.getSheetByName("SOME_SHEETNAME");
var range = sheet.getRange("R2:R");
range.setValues(range.getValues().map(function(row) {
return [row[0].replace(".", ",")];
}));
}
The script works fine as long as only values with a dot can be found in column R. When values that belong to the range are changed to values with a comma, the script gives the error:
TypeError, can't find the function Replace.
Select the column you want to change.
Goto Edit>Find and Replace
In Find area put "."
in Replace with area put ","
The error occurs because .replace is a string method and can't be applied to numbers. A simple workaround would be to ensure the argument is always a string, there is a .toString() method for that.
in your code try
return [row[0].toString().replace(".", ",")];
The locale of your spreadsheet is set to a country that uses commas to seperate decimal places. Zapier however seems to use dots and therefore google sheets interprets the data it gets from Zapier as strings since it can't interpret it as valid numbers.
If you change the locale to United States (under File/Spreadsheet settings) it should work correctly. But you may not want to do that because it can cause other issues.
You got a TypeError because the type was number and not string. You can use an if statement to check the type before calling replace. Also you should convert the type to 'number' to make sure it will work correctly independent of your locale setting.
range.setValues(range.getValues().map(function(row) {
if(typeof row[0] === "string") return [Number(row[0].replace(",", "."))];
else return row;
}));
In this case I convert , to . instead of the other way around since the conversion to number requires a ..
Click on Tools > Script Editor.
Put this on your macros.gs (create one if you don't have any):
/** #OnlyCurrentDoc */
function ReplaceCommaToDot() {
var range = SpreadsheetApp.getActiveRange();
var col = range.getColumn();
var row = range.getRow();
function format(str) {
if(str.length == 0) return str;
return str.match(/[0-9.,]+/)[0]
.replace('.','')
.replace(',','.');
}
var log = [range.getRow(), range.getColumn()];
Logger.log(log);
var values = range.getValues()
for(var row = 0; row < range.getNumRows(); row++){
for(var col = 0; col < range.getNumColumns(); col++){
values[row][col] = format(values[row][col]);
}
}
range.setValues(values);
}
Save. Go back to the spreadsheet, import this macro.
Once the macro is imported, just select the desired range, click on Tools > Macro and select ReplaceCommaToDot
Note: This script removes the original ., and replaces , by .. Ideal if you are converting from US$ 9.999,99 to 9999.99. Comma , and whatever other text, like the currency symbol US$, were removed since Google Spreadsheet handles it with text formatting. Alternatively one could swap . and ,, like from US$ 9.999,99 to 9,999.99 by using the following code snippet instead:
return str.match(/[0-9.,]+/)[0]
.replace('.','_')
.replace(',','.')
.replace('_',',');
An alternative way to replace . with , is to use regex functions and conversion functions in the Sheets cells. Suppose your number is in A1 cell, you can write this function in any new cell:
= IF(REGEXMATCH(TO_TEXT(A1), "."), VALUE(REGEXREPLACE(TO_TEXT(A1), ".", ",")), VALUE(A1))
These functions do the following step:
Convert the number in the target cell to text. This should be done because REGEXMATCH expects a text as its argument.
Check if there is a . in the target cell.
If there is a ., replace it with ,, and then convert the result to a number.
If there is no ., keep the text in the target cell as is, but convert it to a number.
(Note : the Google Sheets locale setting I used in applying these functions is United States)
I have different solution.
In my case, I`m getting values from Google Forms and there it is allowed use only numbers with dot as I know. In this case when I capture data from Form and trigger script which is triggered when the form is submited. Than data is placed in specific sheet in a specific cell, but formula in sheet is not calculating, because with my locale settings calculating is possible only with a comma not dot, that is coming from Google Form.
Then I use Number() to convert it to a number even if it is already set as a number in Google Forms. In this case, Google Sheets script is converting number one more time to number, but changes dot to comma because it is checking my locale.
var size = Number(sizeValueFromForm);
I have not tested this with different locale, so I can`t guarantee that will work for locale where situation is opposite to mine.
I hope this helps someone. I was looking for solution here, but remembered that some time ago I had similar problem, and tried this time too and it works.
=IF(REGEXMATCH(TO_TEXT(F24);"[.]");REGEXREPLACE(F24;"[.]";",");VALUE(F24))
Works for me
If find dot replace with comma if not, put value

using a variable within a string with Google Sheets

I am using Google Apps for Sheets. I am trying to use a defined variable within a string. I know the variable (lastRow) is the number I want (that number being "11") as I can see it in the logs. I have tried different ways of combining the letter "C" with the variable, but nothing works! I know it works as it is used in the "copyValuesToRange" method. Am I trying to do something that cannot be done, or is there a way to add the variable to the A1 notation so that the range will be read as C1:C11? Thanks from a relatively novice newbie!
var lastRow = sheet.getLastRow();
Logger.log(sheet.getLastRow());
// Inserts 1 column after column A=1 (Seq)
sheet.insertColumnsAfter(1,1);
// New column(s) due to added column(s)
var range = sheet.getRange("C1:ClastRow");
//Copied to Col A=1
range.copyValuesToRange(sheet,1,1,1,lastRow);
While writing this, the "Similar Question" box showed a link to "Google script string with a variable". I looked at that, but did not understand it "(!
You dont do it like that, you need to know concatenation.
var lastRow = 11;
console.log("C"+lastRow);
will output:
C11
which is what you're going for.
var range = sheet.getRange("C1:C"+lastRow);

How to set formula by using google spreadsheets app script?

Actually, question is - how to recreate type of formulas:
ArrayFormula(replace(replace(regexreplace(K1:K&"","[-/,. ()]",""),4,0,"-"),8,0,"-"))
into code. Unfortunately, i didn't find it by myself, so I'm asking for help.
Upd.
Let me clarify just a little.
Part of code which was used by me into script:
value = value.replace(/^ /, '').replace(/[. )]/g, 'a').replace(/[+]/g, '').replace(/(aa)/g, '-').replace(/(a)/g, '-').replace(/[(]/g, '-');
value = value.replace(/^-/, '');
value = value.replace(/-$/, ''); range2.setValue(value);
This is example of a result:
"(22)road.CA" - "22-road-CA";
"22roadCA" - is not(eror).
If we working into google spreadsheets we could use formula's which I'm typed before, and in this case, results will be the:
"(22)road.CA" - "22-road-CA";
"22roadCA" - "22-road-CA".
So, how to create right code for it? Mb I should delete all signs, use looping method for check sign by sign, and insert my variant after some count of cell array?
Simple example :
var formulaTargetCell = SpreadsheetApp
.getActiveSpreadsheet()
.getActiveSheet()
.getRange(1, 1, 1, 1);
formulaTargetCell.setFormula('=ArrayFormula(replace(replace(regexreplace(K1:K&"""",""[-/,. ()]"",""""),4,0,""-""),8,0,""-""))');
//or
var formulaTargetCell = SpreadsheetApp
.getActiveSpreadsheet()
.getActiveSheet()
.getRange('B2');
formulaTargetCell.setFormulaR1C1('=ArrayFormula(replace(replace(regexreplace(K1:K&"""",""[-/,. ()]"",""""),4,0,""-""),8,0,""-""))');
There are still some kind of way to set formula in app script that documented in available API of Range

How do I slice strings in Google Apps Script like in Python?

I'm trying to make a Google Sheet that opens to an assigned sheet automatically for a large team using their gmail addresses when accessing it. How do I slice a string in Apps Scripts? The "email.slice" on line three is just something I made up as a place holder.
function onOpen() {
var email = Session.getActiveUser().getEmail();
var username = email.slice[0:-9];
var ss= SpreadsheetApp.openById(username);
SpreadsheetApp.setActiveSpreadsheet(ss);
}
The slice method returns part of the string. You could return all of it, but there's no point in that. There are two parameters, one is optional, the start and end parameters. Start comes first, end is second, and end is optional. If the end parameter is not used, the method automatically goes to the end of the string.
Apps Script uses JavaScript, so any JavaScript reference material that you want to use will give you the answers for almost everything related to basic programming.
In your case, you need to combine slice with indexOf().
var username = email.slice(0, email.indexOf("#"));
Logger.log('username is: ' + username); //VIEW, LOGS to see print out
Substring will work as well
var username = email.substring(0, email.indexOf("#"));
Here is what I ended up doing:
function onOpen() {
var email = Session.getActiveUser().getEmail();
var ldap = email.slice(0,-11);
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName(ldap));
}
Worked well.

Categories