JavaScript

Convert decimal to binary, octal, or hexadecimal in Javascript

In this tutorial, we are going to see how to 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. Hexadecimal numbers usually start with 0x and octal numbers start with 0. To convert a decimal value to hexadecimal, pass the value 16 as a parameter to the number’s toString() method. Similarly, pass the value 8 and 2 as parameters to toString() method to convert it to octal and binary format.
 

 

Script to convert decimal to binary, octal, or hexadecimal in Javascript
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);

Output:

The decimal number is 15
The octal number is 17
The hexadecimal number is f
The binary number is 1111
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *