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;
//default
console.log(num.toString())
//base 2
console.log(num.toString(2))
//base 10
console.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 num to a string without passing any parameters to the toString() method. It converts using the default base 10 and converts the number.
  • In line 7, we convert the number num to a string using the base 2 as a parameter. Then, we print the string value that is returned.
  • In line 10, we convert the number num to a string using the base 10 as a parameter. Then, we print the string value that is returned.