Number object that allows you to convert any
number type value into its
string type representation.
To use the
toString() method, you simply need to call the method on a
number value. The following example shows how to convert the number value
24 into its string representation. Notice how the value of the
str variable is enclosed in double quotation marks:
You can also call the
toString() method immediately on a
number value, but you need to add parentheses
Invalid or unexpected token error.
toString() method can also convert floating and negative numbers as shown below:
toString() method also accepts the
base parameter. The
radix allows you to convert a number from the decimal number system (base 10) to a string representing the number in other number systems.
Valid number systems for conversion include:
- Binary system (base 2) that has 2 digits, 0 and 1
- Ternary system (base 3) that has 3 digits 0, 1, and 2
- Quaternary system (base 4) that has 4 digits, 0, 1, 2 and 3
- And so on up to the Hexatridecimal system (base 36) that has the combination of Arabic numerals 0 to 9 and Latin letters A to Z
radix parameters accept a
number type data with values ranging from
36. Here's an example of converting the decimal number
5 to its binary number (base 2) representation:
The decimal number
5 from the code above is converted to its binary number equivalent of
101 and then converted to a string.
How to Use Other Data Types with the toString() Method
Aside from converting the
number type, the
toString() method is also available for converting other data types into their string representations.
For example, you can convert an
array type into its
string representation as follows:
boolean type to
string as shown below:
var bool = true;
var str = bool.toString();
console.log(str); // "true"
But I think you will most often use the
toString() method to convert a
number to a
string instead of the others. That's what I usually do, too :)
Thanks for reading this tutorial
Until next time!