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

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -