How to Convert Decimal to Binary in JavaScript

Updated onbyAlan Morel
How to Convert Decimal to Binary in JavaScript

Table of Contents

  1. Conclusion

In this post, we'll learn how to convert a decimal number to binary in JavaScript.

Before we start, let's go over what a decimal number and a binary number are.

A decimal number is a number you're most familiar with, one that uses base 10. A binary number is a number that uses base 2, meaning only 0 and 1 are used.

We can convert a decimal number to binary in JavaScript by using the toString() method. This method takes an optional radix parameter, which is the base to convert to.

In this case, we're converting to base 2, so we'll use 2 as the radix.

JAVASCRIPT
const decimalNumber = 10; const binaryNumber = decimalNumber.toString(2); console.log(binaryNumber); // 1010

The toString() method will convert the number you give it, to a string. The radix of 2 means that the number will be converted to binary.

The great thing about toString() is that it can be used to convert any number to a string, including non-integers and even negative numbers.

Here's how to use toString() to convert a non-integer number:

JAVASCRIPT
const nonIntegerNumber = 1.23; const binaryNumber = nonIntegerNumber.toString(2); console.log(binaryNumber); // 1.001110101110000101000111101011100001010001111010111

Here's how to use toString() to convert a negative number:

JAVASCRIPT
const negativeNumber = -13; const binaryNumber = negativeNumber.toString(2); console.log(binaryNumber); // -1101

If you want to wrap this method in a wrapper function, here's how that looks like:

JAVASCRIPT
const decimalToBinary = decimalNumber => decimalNumber.toString(2);

Conclusion

We've learned what a decimal number is, what a binary number is, and how to convert from one to the other in JavaScript.

Hopefully, you've found this post helpful and enjoyed reading it!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.