Skip to content
Blog

Decimal to Binary in JavaScript (With Code)

By Published A short read

      Hi everyone in this article we going to make a function to convert decimal numbers to binary numbers.

Prefer to watch? Here's the video version of this post.

    So before that make sure you are know how to convert the decimal numbers to binary numbers on papers in traditional way. And over here we are just going to implement that logic into code.

    And the language is javascript but the logic can be implemented in any language you want. And we are using node.js as javascript runtime.

Decimal Numbers To Binary Numbers

    code: 

const toBinary = (decimalNumber) => {
    if(decimalNumber == 0) return "0"
    let remainder = []
    while (decimalNumber > 1) {
        remainder.push(decimalNumber % 2)
        decimalNumber = Math.floor(decimalNumber / 2)
    }
    remainder.push(1)
    return remainder.reverse().join("")
}
console.log(toBinary(29))
console.log(toBinary(35))
console.log(toBinary(102))
console.log(toBinary(88))
console.log(toBinary(69))

    output: 

$ node index.js
11101
100011
1100110
1011000
1000101

Thankyou :)