Skip to content

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.

You can convert a string to a number by passing it as an argument to the Number function (don’t use new).

Sample using the Number function
const thisYear = Number('2022'); // 2022
const root2 = Number('1.4142'); // 1.4142
const notANumber = Number('Hello'); // NaN
const empty = Number(''); // 0

If 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.

You can also convert a string to a number with the built-in parseInt function.

Sample using parseInt
const thisYear = parseInt('2022'); // 2022
const root2 = parseInt('1.4142'); // 1
const notANumber = parseInt('Hello'); // NaN
const empty = parseInt(''); // NaN

To convert a number to a string, we recommend using the toString method of the Number object.

Sample using Number.toString
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.

You can also convert a number to a string by passing it as an argument to the String function.

Sample using the String function
const thisYear = String(2022); // '2022'
const pi = 3.1415;
const piText = String(pi); // '3.1415'