Is it possible to convert a number into other base forms using toString() method in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

toString() method is not only used to convert an array into a string but also used to convert a number into other base forms. toString() method can output numbers from base 2 to base 36

Lets' discuss it with an example

Example-1

In the following example, number 46 is converted into various base forms from 2 to 36.

Live Demo

<html>
<body>
<script>
   var Num = 26;
   document.write(
   "The number 26 can be converted in to" + "</br>" +
   "Binary - " + Num.toString(2) + "</br>" +
   "octal - " + Num.toString(8) + "</br>" +
   "Decimal - " + Num.toString(10) + "</br>" +
  "hexadecimal - " + Num.toString(16));
</script>
</body>
</html>

Output

The number 26 can be converted in to
Binary - 11010
octal - 32
Decimal - 26
hexadecimal - 1a

Example-2

In the following example, number 36 is converted into binary, octal, decimal and hexadecimal base forms using toString() method.

Live Demo

<html>
<body>
<script>
   var Num = 36;
   document.write(
   "The number 36 can be converted in to" + "</br>" +
   " Binary - " + Num.toString(2) + "</br>" +
   " octal - " + Num.toString(8) + "</br>" +
   " Decimal - " + Num.toString(10) + "</br>" +
   " hexadecimal -" + Num.toString(16));
</script>
</body>
</html>

Output

The number 36 can be converted in to
Binary - 100100
octal - 44
Decimal - 36
hexadecimal -24
raja
Published on 02-Jul-2019 08:58:35
Advertisements