Skip to content

JavaScript Convert Decimal to Binary

Ramesh Fadatare edited this page Aug 11, 2020 · 1 revision

In this example, we will write a JavaScript function to convert Decimal number to Binary number.

JavaScript Convert Decimal to Binary

function decimalToBinary (num) {
  var bin = []
  while (num > 0) {
    bin.unshift(num % 2)
    num >>= 1 // basically /= 2 without remainder if any
  }
  console.log('The decimal in binary is ' + bin.join(''))
}

decimalToBinary(2)
decimalToBinary(7)
decimalToBinary(35)

Output

The decimal in binary is 10
The decimal in binary is 111
The decimal in binary is 100011
Clone this wiki locally