JavaScript Number toString(): Convert a Number to a String

The JavaScript toString() method is used when we need to convert a number to a string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      let myNumber = 10;
      let myString = myNumber.toString();
      document.getElementById("xyz").innerHTML = typeof myString;
   </script>
   
</body>
</html>
Output

Please note: The typeof operator is used to find the type of value or variable.

JavaScript toString() syntax

The syntax of the toString() method in JavaScript is:

number.toString(x)

The parameter x is optional and refers to an integer value from 2 to 36. This parameter is used when we need to get a number as a string after formatting the number in binary, octal, or hexadecimal form. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      let myNumber = 10;
      let myString = myNumber.toString(16);
      document.getElementById("xyz").innerHTML = myString;
   </script>
   
</body>
</html>
Output

Since the hexadecimal value of 10 is a, the above example produced a on the output.

Please note: 2 for binary, 8 for octal, and 16 for hexadecimal.

The toString() method returns a string as a number.

JavaScript toString() example

Consider the following HTML and JavaScript code as an example demonstrating the "toString()" method in JavaScript:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p>Binary Value of 234 = <span id="abc"></span></p>

   <script>
      let myNumber = 234;
      let myString = myNumber.toString(2);
      document.getElementById("abc").innerHTML = myString;
   </script>
   
</body>
</html>
Output

Binary Value of 234 =

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!