How To Convert Binary To Decimal In Javascript

Binary numbers are commonly encountered in the realm of computer programming. A binary number is a number expressed in the base-2 numeral system, which uses only two symbols, typically 0 and 1, to represent any value. To express these decimal numbers, which use the base-10 numeral system, we frequently need to translate these binary values.

This conversion can be a challenging task for many beginners in programming. However, there are a number of built-in functions in JavaScript that make this translation simpler for programmers. We’ll go over the detailed steps in this blog for converting binary to decimal in JavaScript.

So, let’s dive in!

Why Is There A Need to convert binary to decimal in javascript

Some of the reason how to convert binary to decimal in javascript are:-

  • Human Readability: Binary numbers are not easily readable by humans, as they are represented using only two digits (0 and 1). However, because decimal numbers use 10 digits (0–9) to represent any value, they are well-known and simple to comprehend.
  • Mathematical Operations: Most mathematical operations are easier to perform with decimal numbers than with binary numbers.
  • User Input: Sometimes, users may enter data in binary form. We must first convert this data to decimal format before processing it.
  • Display: In some cases, we need to display binary numbers as decimal numbers for presentation purposes. For instance, in a program that involves calculations with monetary values, it is better to display results in decimal format.
  • Compatibility: Many libraries, frameworks, and APIs use decimal numbers. Therefore, converting binary numbers to decimal format makes them compatible with these tools, enabling seamless integration into a project.

Overall, converting binary to decimal in JavaScript is an essential task that helps us work with binary data and enables compatibility with other tools and systems that use decimal numbers.

Approaches to convert binary to decimal in JavaScript

Approaches to convert binary to decimal in JavaScript

There are three methods, how to change binary to decimal in javascript. Methods are listed below:-

  • Using the parseInt() method with a radix of 2
  • Using the reduce() method
  • Using the for loop

Let’s have a look.

1. Using the parseInt() method with a radix of 2

In javascript, the parsInt() function is a built-in function that accepts two arguments: the string to be converted and the number system’s base (optional).

By giving a radix of 2, we may use this function to transform a binary string into a decimal number.

Sample Code:-

const binaryNumber = ‘101011’;

//here we are using the function
const decimalNumber = parseInt(binaryNumber, 2);

console.log(decimalNumber);

Output:-

43

Explanation of code:-

  • The binaryNumber variable stores the binary number as a string.
  • The binary text to be converted and the radix, which is set to 2 in this case to indicate that the string is a binary number, are the two inputs that the parseInt() method requires.
  • The resulting decimal number is stored in the decimalNumber variable and is outputted to the console.

2. Using the reduce() method

The reduce() method is a functional approach to converting a string of binary digits to a decimal number. This approach involves treating the string as an array of characters and then using reduce() to iterate the array and compute the decimal equivalent of the binary number. Here’s an example:

Sample Code:-

const binaryNumber = ‘101011’;

//here we are using the function
const decimalNumber = binaryNumber.split('').reduce((accumulator, currentValue) => {
  return accumulator * 2 + parseInt(currentValue);
}, 0);

console.log(decimalNumber);

Output:-

43

Explanation of code:-

  • The ‘binaryNumber’ variable stores the binary number as a string.
  • The ‘split()’ is used to convert the string into an array of individual digits.
  • The ‘reduce()’ method iterates through each digit in the array, accumulating the decimal value as it goes.
  • Initialized at 0, the accumulator variable is then multiplied by 2, and its value is increased by the current value for each digit in the array.
  • The resulting decimal number is stored in the ‘decimalNumber’ variable and is outputted to the console.

3. Using for loop

We can also use a for loop to convert binary to decimal in JavaScript. Here’s an example:

Sample Code:-

const binaryNumber = '101011';
let decimalNumber = 0;

for (let i = binaryNumber.length - 1, j = 0; i >= 0; i--, j++) {
  decimalNumber += binaryNumber[i] * 2 ** j;
}

console.log(decimalNumber);

Output:-

43

Explanation of code:-

  • The binaryNumber variable stores the binary number as a string.
  • Beginning with the rightmost digit (the least significant bit), the for loop iterates through each digit in the string.
  • The decimalNumber variable is initially set to 0 and is then incremented by the current digit multiplied by 2 to the power of the current position in the string.
  • The resulting decimal number is stored in the decimalNumber variable and is outputted to the console.

Best approach:- Using the parseInt() method with a radix of 2

If we were to choose the best approach among them, I would recommend using the parseInt() method with a radix of 2. Some reasons are:-

  • Simplicity: Using the parseInt() method is a simple and straightforward way to convert binary to decimal. It only requires one line of code and no additional calculations.
  • Readability: The widely used and accepted way for converting strings to numbers in JavaScript is the parseInt() method.People who read the code will get no trouble understanding what it does.
  • Performance: A built-in function with excellent performance in terms of speed and memory utilization is the parseInt() method.

Sample Problem how to convert binary to decimal in javascript

Sample Problem 1:- Using the parseInt() method with a radix of 2

Problem Statement:- Anupam is building an e-commerce website where users can enter the quantity of a product in binary form. He needs to convert the binary quantity to decimal so that he can calculate the total price. Please help Anupam to make code that converts binary to decimal.

Solution:-

  • The binaryQuantity variable stores the binary quantity as a string.
  • The pricePerItem variable stores the price of one item.
  • The totalPrice variable is calculated by multiplying the pricePerItem by the decimalQuantity.
  • The resulting total price is outputted to the console.

Solution Code:-

const binaryQuantity = ‘10110’;
const pricePerItem = 9.99;
const decimalQuantity = parseInt(binaryQuantity, 2);
const totalPrice = pricePerItem * decimalQuantity;

console.log(totalPrice);

Output:-

219.78

Sample Problem 2:- Using the reduce() method

Problem Statement:- Samreen is working on a project that requires her to perform bitwise operations on binary numbers. She needs to convert the binary numbers to decimal form so she can perform the operations. Help Samreen in building the code.

Solution:-

  • The binaryNumber1 and binaryNumber2 variables store the binary numbers as strings.
  • The split() method is used to convert each binary number to an array of individual digits.
  • The reduce() method is used to convert each binary number to its decimal form.
  • The bitwise AND and OR operations are performed on the resulting decimal numbers using the & and | operators.
  • The results of the operations are outputted to the console.

Solution Code:-

const binaryNumber1 = '101010';
const binaryNumber2 = '110011';
const decimalNumber1 = binaryNumber1.split('').reduce((accumulator, currentValue) => {
  return accumulator * 2 + parseInt(currentValue);
}, 0);
const decimalNumber2 = binaryNumber2.split('').reduce((accumulator, currentValue) => {
  return accumulator * 2 + parseInt(currentValue);
}, 0);

console.log(decimalNumber1 & decimalNumber2);
console.log(decimalNumber1 | decimalNumber2);

Output:-

34
59

Sample Problem 3:- Using the for loop

Problem Statement:- Pratik has a task to develop a game that requires generating random binary numbers and converting them to decimal form so that we can compare them to the user’s input. Help Pratik to do this task.

Solution:-

  • The generateBinaryNumber() function generates a random binary number of the specified length.
  • The binaryNumber variable stores the generated binary number.
  • The for loop iterates through each digit in the binary number, converting it to decimal form and accumulating the decimal value.
  • The resulting decimal number is outputted to the console, along with the original binary number.

Solution Code:-

function generateBinaryNumber(numDigits) {
  let binaryNumber = '';
  for (let i = 0; i < numDigits; i++) {
    binaryNumber += Math.floor(Math.random() * 2);
  }
  return binaryNumber;
}

const binaryNumber = generateBinaryNumber(6);
let decimalNumber = 0;

for (let i = binaryNumber.length - 1, j = 0; i >= 0; i--, j++) {
  decimalNumber += binaryNumber[i] * 2 ** j;
}

console.log(`Binary number: ${binaryNumber}`);
console.log(`Decimal number: ${decimalNumber}`);

Output:-

Binary number: 010111
Decimal number: 23

Conclusion

There are several ways to convert from binary to decimal in javascript.Using the parseInt() method with a radix of 2 is the simplest and most concise approach. It’s also highly optimized for performance and easily readable by other developers.

The conventional method of using a for loop gives more precise control over the conversion process, but it involves more code and could be slower than other methods.

Before choosing a solution, take into account the requirements of your specific use case as well as the readability and performance of the code.