/  Technology   /  Convert decimal to binary, octal, or hexadecimal in Javascript
Convert decimal to binary, octal, or hexadecimal in Javascript

Convert decimal to binary, octal, or hexadecimal in Javascript

      

 In JavaScript we can convert decimal to binary, octal or hexadecimal using the toString method by giving the correct base as a parameter. Numbers in JavaScript are base 10 by default .In the below code we have declared a variable decimal with 15 number and console logged “The decimal number is ” with the decimal using the concat() method in javascript.

For converting a number from decimal to octal. We are using the number.toString() method of javascript.It takes the parameter which is the base of the converted string.

The number holds in a decimal format which needs to be converted. Here we are using decimal in place of number and passed 8 in toString method, which in turn 17 as the octal.

Hexadecimal numbers usually start with 0x and octal numbers start with 0. In declaring hexadecimal we are using 15 as the number and 16 base as a parameter. Thus, when we console log we get “f” as the result as f indicates 15 in hexadecimal format.

For Converting decimal to binary we are taking base a 15 and declaring the variable binary. Using the toString() method with parameter of 2 we get tne binary result as 1111.

Thus using the toString method we can convert decimal to binary, octal and hexadecimal in JavaScript.

<!DOCTYPE html>
<html>
<head></head>
<body>   
   <script>
   var decimal = 15;
console.log("The decimal number is " + decimal);
var octal = decimal.toString(8);
console.log("The octal number is " + octal);
var hexadecimal = decimal.toString(16);
console.log("The hexadecimal number is " + hexadecimal);
var binary = decimal.toString(2);
console.log("The binary number is " + binary);
   </script>
</body>
</html>

Output:

 

Leave a comment