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.



Share this Tutorial / Exercise on : Facebook and Twitter

JavaScript: Tips of the Day

arrow function

const user = {
	email: "[email protected]",
	updateEmail: email => {
		this.email = email
	}
}

user.updateEmail("[email protected]")
console.log(user.email)

The updateEmail function is an arrow function, and is not bound to the user object. This means that the this keyword is not referring to the user object, but refers to the global scope in this case. The value of email within the user object does not get updated. When logging the value of user.email, the original value of [email protected] gets returned.

Ref: https://bit.ly/2IUFeTa