Convert between strings and numbers
This article uses Office Scripts to explain how to convert strings to numbers and numbers to strings, with sample code.
Convert strings to numbers
Section titled “Convert strings to numbers”Using the Number function
Section titled “Using the Number function”You can convert a string to a number by passing it as an argument to the Number function (don’t use new).
const thisYear = Number('2022'); // 2022
const root2 = Number('1.4142'); // 1.4142
const notANumber = Number('Hello'); // NaN
const empty = Number(''); // 0If the string contains characters that can’t be interpreted as a number, the result is NaN (Not a Number). Note that an empty string or a string that contains only whitespace becomes 0.
Using the parseInt function
Section titled “Using the parseInt function”You can also convert a string to a number with the built-in parseInt function.
const thisYear = parseInt('2022'); // 2022
const root2 = parseInt('1.4142'); // 1
const notANumber = parseInt('Hello'); // NaN
const empty = parseInt(''); // NaNConvert numbers to strings
Section titled “Convert numbers to strings”Using Number.toString
Section titled “Using Number.toString”To convert a number to a string, we recommend using the toString method of the Number object.
const thisYear = (2022).toString(); // '2022'
const pi = 3.1415;const piText = pi.toString(); // '3.1415'
const binary = (100).toString(2); // '1100100'If you specify a radix (2 to 36) as the argument, you get a string that represents the number in that base. For example, toString(2) returns a string that represents the number in binary.
Using the String function
Section titled “Using the String function”You can also convert a number to a string by passing it as an argument to the String function.
const thisYear = String(2022); // '2022'
const pi = 3.1415;const piText = String(pi); // '3.1415'