# 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:

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:

Live Demo:

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

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿