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

Leave A Reply

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

You May Also Like

You might want to filter an array in JavaScript by passing the filter criteria and return the filtered array. In...
You can flatten a 2-D array in JavaScript using the concat and apply method as shown in the below code...
Assume that you have an angle in degree and you wish to convert it to radians in JavaScript so that...