Convert Decimal to Octal , Hexadecimal and Binary Value in JavaScript

If you have a decimal number in JavaScript and want to convert it to its equivalent octal , hexadecimal and binary value , you can use the toString method by passing the right radix as parameter.

How to Convert Decimal number to Octal , Hexadecimal and Binary in JavaScript ?

The numbers in JavaScript are by default of base 10. The Hexadecimal numbers usually begins with 0x and octal number begins with 0.

To convert a decimal value to octal , pass the value 16 as parameter to the toString method of the number. Similarly , pass the value 8 and 2 as parameter to the toString method respectively to convert it to octal and binary format.

<script type="text/javascript">
    var decimalNumber = 10;
    console.log("Decimal Number is " + decimalNumber);

    var octalNumber = decimalNumber.toString(8);
    console.log("Octal Number is " + octalNumber);

    var hexadecimalNumber = decimalNumber.toString(16);
    console.log("Hexadecimal Number is " + hexadecimalNumber);

    var binaryNumber = decimalNumber.toString(2);
    console.log("Binary Number is " + binaryNumber);
</script>

image