One cell in a Google Sheets document holds a value given by a SUM of cells formatted as "elapsed hours":"elapsed minutes". Attempting to make calculations in a custom script on this cell will throw errors. Further investigation using typeof() function will show this as "object". How can I convert the cell value to number? Attempted parseInt() or parseFloat() unsuccessfully….
In the linked sheet here you will see that:
- cell A1 having a formula that returns
288:00
formatted as duration, -
cell A2, having
=daysHrsMins(A1)
, that returns a negative value,-3.179.700.519.840.000,00
from the following function:function daysHrsMins(input) { return input*1440; }
Regional settings: Italy
Timezone settings: (GMT +1) Paris
Best Answer
Short answer
On Google Sheets durations are just a display format for date values, so when a custom function takes a duration it's treated as a date object.
Explanation
Doing arithmetic operations
When we are doing arithmetic operations on dates/times/duration, we should bear in mind the following:
Google Sheets
Google Apps Script / JavaScript
Display format
Google Sheets
[h]:mm:ss.00
).Google Apps Script / JavaScript
Transfer of dates between Google Sheets and Google Apps Script
When a date value is transferred from Google Sheets to Google Apps Script or vice versa it is automatically converted considering the timezone of the spreadsheet.
Solution
As Google Sheets and Google Apps Scripts duration/date handling is different the simplest solution is to do the conversion from date/duration to number on the origin application.
On Google Sheets we could use TO_PURE_NUMBER to do this conversion:
For certain use cases it could be convenient to use a JavaScript library like moment.js
References
Related Q&A from this site:
Related Q&A from Stack Overflow