Maximus - 2 years ago 110

Javascript Question

Javascript has the function

`parseInt()`

`parseInt("101", 2) // 5`

However, I need to convert binary fraction to its decimal equivalent, like:

`0.101 = 0.625`

I can write my own function that would calculate the result like the following:

`1 * Math.pow(2, -1) + 0*Math.pow(2, -2) + 1*Math.pow(2, -3) // 0.625`

But I'm wondering whether there is anything standard already.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You can split the number (as string) at the dot and treat the integer part with an own function and the fraction part with another function for the right value.

The solution works with other bases as well.

```
function convert(v, base) {
var parts = v.toString().split('.');
base = base || 2;
return parseInt(parts[0], base) + (parts[1] || '').split('').reduceRight(function (r, a) {
return (r + parseInt(a, base)) / base;
}, 0);
}
document.write(convert(1100) + '<br>');
document.write(convert(0.0011) + '<br>');
document.write(convert(1100.0011) + '<br>');
document.write(convert('ABC', 16) + '<br>');
document.write(convert('0.DEF', 16) + '<br>');
document.write(convert('ABC.DEF', 16) + '<br>');
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**