How to get a string representation of a number in JavaScript?


Use the toString() method to get the string representation of a number. You can try to run the following code to print a string representation of numbers like 20, -40, 15.5 −

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <script>
         var num1 = 25;

         document.write(num1.toString()+"<br>");
         document.write((30.2).toString()+"<br>");

         var num2 = 3;

         document.write(num2.toString(2)+"<br>");
         document.write((-0xff).toString(2));
      </script>
   </body>
</html>

Output

25
30.2
11
-11111111

Above, you can see we added a parameter to the toString() method. This is an optional parameter, which allows you to add an integer between 2 and 36, which is the base for representing numeric values.

Updated on: 17-Jun-2020

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements