javascript - How to convert binary fraction to decimal -


javascript has function parseint() can convert integer in binary form decimal equivalent:

parseint("101", 2) // 5 

however, need convert binary fraction decimal equivalent, like:

0.101 = 0.625 

i can write own function calculate result following:

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

but i'm wondering whether there standard already.

you can split number (as string) @ dot , treat integer part own function , fraction part function right value.

the solution works other bases 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>');


Comments

Popular posts from this blog

wireshark - USB mapping with python -

c++ - nodejs socket.io closes connection before upgrading to websocket -

Deploying Qt Application on Android is really slow? -