Skip to content
Advertisement

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.

Advertisement

Answer

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(".", ",")];
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement