What is the number.toString() method in TypeScript?
Overview
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.
Syntax
Here is the syntax of the toString() method:
num.toString(val)
Parameter value
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.
Return value
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.
Example
let num = 15;//defaultconsole.log(num.toString())//base 2console.log(num.toString(2))//base 10console.log(num.toString(10))
Explanation
In the code snippet given above:
- In line 1, we declare and initialize the number
num. - In line 4, we convert the number
numto a string without passing any parameters to thetoString()method. It converts using the default base10and converts the number. - In line 7, we convert the number
numto a string using the base2as a parameter. Then, we print the string value that is returned. - In line 10, we convert the number
numto a string using the base10as a parameter. Then, we print the string value that is returned.