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!
Create an RSS Reader in Node
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
How to deploy a Deno app using Docker
Getting Started with Deno
How to deploy a MySQL Server using Docker
Getting Started with Sass
Learn how to use v-model with a custom Vue component
Using Puppeteer and Jest for End-to-End Testing
Getting Started with Handlebars.js
Getting Started with React
Setting Up Stylus CSS Preprocessor
