In this article, I will be sharing an easy way to convert a decimal number to a binary number using javascript.
Decimal Number to Binary Number using Javascript
function decimalToBinary(num) { let binary = [] while (num > 0) { binary.push(num % 2) num = Math.floor(num / 2) } console.log(binary.reverse().join('')) } decimalToBinary(10) // Result: 1010
If we check the code, I have used a while loop for the iteration. I have initialized an empty array called binary. I am taking the next quotient using the Math.floor method and dividing by 2 on the input number num and assigning it back to it. I am running a while loop for iteration until the input number num is greater than 0. Before updating the quotient into a num variable, I am pushing the reminder into the binary array.
Now, we have all the reminders in the binary array. To get the binary number, we need to reverse the binary array and make it a string.
There are many ways to do it but this can be one of the easy ways to implement it.