Maximus Maximus - 5 months ago 10
Javascript Question

How to convert binary fraction to decimal

Javascript has the function

parseInt()
which can help convert integer in a binary form into its decimal equivalent:

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.

Answer

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>');