Skip to content

JavaScript toString() function | Number to a string

  • by

JavaScript toString() function is used to convert the number to a string. This method actually returns strings representing the specified Number object.

num.toString(radix)

radix (optional): The base to use. Must be an integer between 2 and 36. Base 2 is binary Base 8 is octal Base 16 is hexadecimal.

Use this method when needs to be displayed number as a text (like in HTML), or when an object needs to be used as a string.

Example JavaScript toString() method

A simple example code converts a number to a string.

<!DOCTYPE html>
<html>

<body>

  <script>
    let num = 15;
    let text = num.toString();

    console.log(text)
    console.log(typeof(text))
  </script>

</body>
</html>

Output:

JavaScript toString() function

Another example code

  <script>
    
    var num = 2;
    document.write("Output : " + num.toString(2));          

  </script>

Output: 10

Convert a number to a string, using base 2 (binary):

  <script>
    
    let num = 15;
    let text = num.toString(2);       
    console.log(text)

  </script>

Output: 1111

Do comment if you have any doubts or suggestions on this JS toString() function.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading