toString() in JavaScript – How to Convert Number to String
toString() converts a number to a string of a specified radix.
Syntax of the toString()
Method
toString()
accepts only one optional argument. Here is the syntax:
number.toString(radix);
The radix
argument specifies the base into which you wish to convert the number.
note
- Radix must be an integer between
2
and36
inclusive. Otherwise,toString()
will return anUncaught RangeError
. - Suppose you omit the
radix
argument. In that case, the computer will assume a radix of10
(base ten). - Suppose you provide a negative number. In such a case, the computer will preserve the negative sign.
Example 1: Convert 45
to a Decimal String
(45).toString();
// The invocation above will return: "45"
Note that the snippet above is equivalent to:
(45).toString(10);
// The invocation above will return: "45"
note
We wrapped 45
in parentheses to make the computer evaluate its data type before using toString()
to convert it to a string value. (Learn more about how the computer evaluates an item's data type.
Example 2: Convert 45
to a Binary String
(45).toString(2);
// The invocation above will return: "101101"
Example 3: Convert Negative 45
to a Binary String
(-45).toString(2);
// The invocation above will return: "-101101"
Example 4: Convert 45
to an Octal String
(45).toString(8);
// The invocation above will return: "55"
Example 5: Convert 45
to a Hexadecimal String
(45).toString(16);
// The invocation above will return: "2d"
Example 6: Convert 45
to a Vigesimal String
(45).toString(20);
// The invocation above will return: "25"
Overview
This article discussed what toString()
is. We also used examples to see how it works.