Javascript Binary Converter loses precision with increased digits

I recently created a program that converts a binary numeric string to a decimal number. It seems to work fine until the string reaches about 15 digits and then starts going back about 1 or 2 spaces (i.e. 1011010110100101001 will return 372008 instead of 372009). Once the string has about 20 digits, it just returns NaN. Any ideas on what's going on?

function binaryConverter2(num) {
    var numString = num.toString(),
        total = 0,
        i = numString.length-1,
        j = 1;

    while(i >= 0) {
        total += (numString[i] *j);

        j = j*2;
        i --;
        console.log(total);
    }

    return total;
} 

      

+3


source to share


1 answer


The issue is caused by the precision of JavaScript floating point numbers. For details, see How to deal with floating point precision in JavaScript? ...

I created a jsbin version of your function that shows that the error is due to the fact that you are sending a floating point number greater than the floating point precision can store it accurately and then convert that to a string. If you think of a decimal number represented by 1011010110100101001 and not a binary number, then you will realize that this is a very large number.



http://jsbin.com/heluyut/1/edit?js,console

console.log(numString);//"1011010110100101000" notice the missing 1 on the right

      

+1


source







All Articles