toString() in JavaScript – How to Convert Number to String
toString() converts a number to a string of a specified radix.
toString()
is sometimes written as Number.prototype.toString()
because it is a method of the Number
object's prototype
property.
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.
- 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.
Examples of the toString()
Method
Below are examples of the toString()
method.
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"
We wrapped 45
in a grouping operator to make browsers interpret the dot correctly as a property accessor used to access the number's toString()
method. Learn more about how browsers interpret a method's dot.
Get creative with your projects
Convert 45
to a binary string
(45).toString(2);
// The invocation above will return: "101101"
Convert negative 45
to a binary string
(-45).toString(2);
// The invocation above will return: "-101101"
Convert 45
to an octal string
(45).toString(8);
// The invocation above will return: "55"
Convert 45
to a hexadecimal string
(45).toString(16);
// The invocation above will return: "2d"
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.
Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.
Tweet this article