Categories
JavaScript Answers

How to convert a decimal string to a binary string with JavaScript?

Spread the love

Sometimes, we want to convert a decimal string to a binary string with JavaScript.

In this article, we’ll look at how to convert a decimal string to a binary string with JavaScript.

How to convert a decimal string to a binary string with JavaScript?

To convert a decimal string to a binary string with JavaScript, we can use the JavaScript number’s toString method.

For instance, we write:

const num = '123'
const b = Number(num).toString(2)
console.log(b)

We call Number with num to convert num to a number.

Then we call toString on the returned number with 2 to convert it to a binary string.

As a result, b is '1111011'.

Conclusion

To convert a decimal string to a binary string with JavaScript, we can use the JavaScript number’s toString method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.