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 toString() method in JavaScript is:

number.toString(x)

The parameter x is optional, refers to a integer value from 2 to 36. This parameter is used when we need to get number as string after formatting the number in binary, octal, 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. Therefore the above example produced a as output.

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

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

JavaScript toString() Example

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 »