w3resource

JavaScript: Convert a binary number to a decimal number

JavaScript Math: Exercise-2 with Solution

Write a JavaScript function to convert a binary number to a decimal number.

Test Data: console.log(bin_to_dec('110011')); console.log(bin_to_dec('100')); 51 4

Visual Presentation:

JavaScript: Math - Convert a binary number to a decimal number

Sample Solution:

JavaScript Code:

// Define a function named bin_to_dec that takes a binary string as input and converts it to decimal.
function bin_to_dec(bstr) { 
    // Convert the binary string to a decimal integer using parseInt, removing any non-binary characters.
    return parseInt((bstr + '').replace(/[^01]/gi, ''), 2);
}

// Output the decimal conversion of the binary string '110011' to the console.
console.log(bin_to_dec('110011'));
// Output the decimal conversion of the binary string '100' to the console.
console.log(bin_to_dec('100'));

Output:

51
4

Explanation:

In the exercise above,

  • The code defines a function named "bin_to_dec()" which takes a binary string (bstr) as input.
  • Inside the function, it converts the binary string to a decimal integer using the "parseInt()" function. The regular expression (/[^01]/gi, '') is used with "replace()" to remove any characters that are not '0' or '1' from the binary string.
  • The "parseInt()" function is then used to convert the cleaned binary string to a decimal integer, specifying base 2 (binary) as the second argument.
  • The function returns the decimal and integer representation of the binary string.

Flowchart:

Flowchart: JavaScript Math- Convert a binary number  to a decimal number

Live Demo:

See the Pen javascript-math-exercise-2 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to convert a number from one base to another.
Next: Write a JavaScript function to convert a decimal number to binary, hexadecimal or octal number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-math-exercise-2.php