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 Solid
Getting Started with Svelte
Create an RSS Reader in Node
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
How to deploy a .NET app using Docker
How to deploy an Express app using Docker
How to deploy a Node app using Docker
Using Push.js to Display Web Browser Notifications
Setting Up a Local Web Server using Node.js
Using Axios to Pull Data from a REST API
How To Create a Modal Popup Box with CSS and JavaScript
