Skip to main content

Converts between numbers and mutual values

This time, we will use an Office script to explain the method of converting each of the strings, numerical values, and character strings together with the sample code.

Difference from VBA

In VBA, operations between different types of data are errors, but are allowed in Office scripts.

For example, if a string and a numerical value are added, the numerical value is implicitly cast as a string, and even if the string can be converted to a numerical value, it is processed as a string.

Transformation into an implicit character string
const value1 = '150';

const value2 = 200;

// The output result is "150200", not 350
console.log(value1 + value2); //150200

If the numerical data is stored as a string, it will be explicitly necessary to convert.

Conversion from string to numerical values

How to use Number constructor

By specifying a string in the argument of the Number constructor, the string can be converted to a numerical value.

Sample using Number constructor
const thisYear = Number('2022'); // 2022

const root2 = Number('1.4142'); // 1.4142

const notANumber = Number('hello'); // NaN

const empty = Number(''); // 0

How to use the parseInt function

By using the parseInt function provided as standard, you can convert character strings to numerical values.

Sample using parseInt function
const thisYear = parseInt('2022'); // 2022

const root2 = parseInt('1.4142'); // 1

const notANumber = parseInt('hello'); // NaN

const empty = parseInt(''); // NaN
important point

If you use the parseInt function, it will be cut off if you include the decimal point.

Conversion from numerical values to string

How to use Number.toString

For conversion from numerical values to character strings, we recommend using the toString method provided in the number object.

Number."Sample
const thisYear = (2022).toString(); // 2022

const pi = 3.1415;
const enshuritsu = pi.toString(); // '3.1415'

const binary = (100).toString(2); // '1100100'

If you specify the number in the argument, you can receive the number that the specified value is the number.For example, if you specify tostring(2), a value that converts the target number to a binary number is returned.

How to use String constructor

By specifying a numerical value in the argument of the String constructor, it can be converted from a numerical value to a string.

Sample using String's constructor
const thisYear = String(2022); // 2022

const pi = 3.1415;
const enshuritsu = String(pi); // '3.1415'