The toString()
method is used to convert a number to a string. We call this method on the number that we want to convert into a string.
Here is the syntax of the toString()
method:
num.toString(val)
This method accepts val
as an optional parameter with a default of base 10
. The value of val
must be an integer between 2
and 36
.
This method returns a string for the given number after it converting with the given val
value.
Let's look at an example of this.
let num = 15;//defaultconsole.log(num.toString())//base 2console.log(num.toString(2))//base 10console.log(num.toString(10))
In the code snippet given above:
num
.num
to a string without passing any parameters to the toString()
method. It converts using the default base 10
and converts the number.num
to a string using the base 2
as a parameter. Then, we print the string value that is returned.num
to a string using the base 10
as a parameter. Then, we print the string value that is returned.