Cloud Training (Online)

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);


Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.