The toNumber()
function converts its argument to a number if it can do so. It is useful for converting strings, Booleans, and dates to numbers.
toNumber(string)
toNumber(Boolean)
toNumber(date)
Code language: JavaScript (javascript)
Unlike unaryPlus, toNumber()
can convert dates to numbers. When used to convert a date, toNumber will convert it to its corresponding Unix timestamp; this behavior matches that of the timestamp function.
Good to know: If a string starts with a number and contains letter chracters as well,toNumber()
will return just that starting number. However, if the string does not start with a number, toNumber()
will output nothing – even if the string contains a number elsewhere.
Example Formulas
toNumber("42") // Output: 42 (number)
toNumber("42 rabbits jump 100 times") // Output: 42
toNumber("I have 42 rabbits.") // Output: blank
toNumber(true) // Output: 1
toNumber(false) // Output: 0
toNumber(5>3) // Output: 1
toNumber(now()) // Output: 1655757000000 (changes with now()'s value)
Code language: JavaScript (javascript)
Example Database
This example database is a simple habit tracker. Each property represents a different habit, and the Habits formula property adds them up and outputs a string reporting the number of habits completed on that day.
View and Duplicate Database
“Habits” Property Formula
// Compressed
format(toNumber(prop("💧")) + toNumber(prop("🏃♂️")) + toNumber(prop("🏋️♀️")) + toNumber(prop("🥦"))) + "/4" + if((toNumber(prop("💧")) + toNumber(prop("🏃♂️")) + toNumber(prop("🏋️♀️")) + toNumber(prop("🥦"))) == 1," Habit"," Habits")
// Expanded
format(
toNumber(
prop("💧")
) +
toNumber(
prop("🏃♂️")
) +
toNumber(
prop("🏋️♀️")
) +
toNumber(
prop("🥦")
)
) +
"/4" +
if(
(
toNumber(
prop("💧")
) +
toNumber(
prop("🏃♂️")
) +
toNumber(
prop("🏋️♀️")
) +
toNumber(
prop("🥦")
)
) == 1,
" Habit",
" Habits"
)
Code language: JavaScript (javascript)
This formula uses toNumber()
to convert the Boolean output of each habit’s checkbox value into a number – either 1
or 0
. It then adds up all the numbers to get a total number of habits completed for the day.
The format function is then used to convert this number into a string so that it can be combined with the other string elements in the formula.
Finally, an if statement uses the same process to determine if the total number of habits completed is equal to 1
. If so, it outputs “Habit”; if not, it outputs the plural “Habits”.