How to Convert Decimal to Binary in JavaScript
Table of Contents
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.
JAVASCRIPTconst 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:
JAVASCRIPTconst nonIntegerNumber = 1.23;
const binaryNumber = nonIntegerNumber.toString(2);
console.log(binaryNumber); // 1.001110101110000101000111101011100001010001111010111
Here's how to use toString()
to convert a negative number:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- Getting Started with Deno
- How to deploy a Node app using Docker
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Setting Up a Local Web Server using Node.js