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!
Getting Started with TypeScript
Getting Started with Solid
Managing PHP Dependencies with Composer
How to Set Up Cron Jobs in Linux
How to build a Discord bot using TypeScript
How to deploy a Deno app using Docker
How to deploy a Node app using Docker
Build a Real-Time Chat App with Node, Express, and Socket.io
Learn how to build a Slack Bot using Node.js
Creating a Twitter bot with Node.js
Using Push.js to Display Web Browser Notifications
Building a Real-Time Note-Taking App with Vue and Firebase
