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

Pictorial Presentation:

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

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Binary number to a decimal number</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function bin_to_dec(bstr) { 
    return parseInt((bstr + '')
    .replace(/[^01]/gi, ''), 2);
}
console.log(bin_to_dec('110011'));
console.log(bin_to_dec('100'));

Sample Output:

51
4

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.



JavaScript: Tips of the Day

Sort Number Arrays

JavaScript arrays come with a built-in sort method. This sort method converts the array elements into strings and performs a lexicographical sort on it by default. This can cause issues when sorting number arrays. Hence here is a simple solution to overcome this problem.

[0,10,4,9,123,54,1].sort((a,b) => a-b);
>>> [0, 1, 4, 9, 10, 54, 123]

You are providing a function to compare two elements in the number array to the sort method. This function helps us the receive the correct output.

Ref: https://bit.ly/3adlwNy