Mees Mouwen
Mees Mouwen

Reputation: 37

Google sheets cannot coerce string to value

I have an issue.

I am using this formula:

      function import2(url) {
        var html, content = "";
        var response = UrlFetchApp.fetch(url);

        if (response) {
          html = response.getContentText();

          if (html)
            content = html.match(
              /<td class="line text">\s*EUR\s+(\d[\d,]*)<\/td>/)[1];
          // Logger.log(content);
          parseFloat(content);
        }
        return content; //Number
      }


It can only import values from the following website: Stock price (https://www.morningstar.nl/nl/funds/snapshot/snapshot.aspx?id=F00000QIPC)

When using the this for url it returns: 20,05, however this cannot be coerced to a number to make calculations with it. Can anybody help me understand why this is?

I also tried:

      function import2(url) {
        var html, content = "";
        var response = UrlFetchApp.fetch(url);

        if (response) {
          html = response.getContentText();

          if (html)
            content = html.match(
              /<td class="line text">\s*EUR\s+(\d[\d,]*)<\/td>/)[1];
          // Logger.log(content);
          parseFloat(content);
        }
        return Number(content); //<-- changed
      }

The last return value is changed to Number(). With this code it gives an error right away and says the returned value is not a number.

I think the issue might be with \s*EUR\s+(\d[\d,]*) But I am unsure if this is the case

Any help would be greatly appreciated!

Upvotes: 1

Views: 266

Answers (1)

Tanaike
Tanaike

Reputation: 201388

How about this modification?

As a simple modification, how about replacing , to . for your below script using replace()? By this, 20,05 is returned as the number of 20.05.

Modified script:

function import2(url) {
  var html, content = "";
  var response = UrlFetchApp.fetch(url);

  if (response) {
    html = response.getContentText();

    if (html)
      content = html.match(
        /<td class="line text">\s*EUR\s+(\d[\d,]*)<\/td>/)[1].replace(",", ".");  // <--- Modified
    // Logger.log(content);
    parseFloat(content);
  }
  return Number(content); //<-- changed
}

Note:

  • When you want to use 20,05 to 2005, please modify replace(",", ".") to replace(",", "").

Reference:

Upvotes: 2

Related Questions