How to convert decimal to binary in JavaScript

How to convert decimal to binary in JavaScript
March 4, 2023 0 comments
1 min read 59 Views

Use the toString() method to convert a decimal number to its binary representation.

Here's an example code snippet:

const decimalNumber = 10; // decimal number to convert to binary

const binaryNumber = decimalNumber.toString(2); // convert to binary

console.log(binaryNumber); // outputs "1010"

In this example, the toString() method is called on the decimal number 10 with a parameter of 2, which specifies that the number should be converted to binary. The resulting binary string "1010" is stored in the binaryNumber variable, which is then printed to the console. Note that the toString() method can also be used to convert numbers to other bases, such as octal or hexadecimal, by passing in different parameters.

For example, to convert a decimal number to octal, you would call toString(8), and to convert to hexadecimal, you would call toString(16).

Login To Read Full Article

0 Comments

My Account