Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Binary converter looses accuracy with increased digits

Tags:

javascript

I recently created a program that converts a binary number string to a decimal number. It seems to work fine until the string reaches around 15 or so digits in length and then it starts to be off by around 1 or 2 places (ie 1011010110100101001 returns 372008 instead of 372009). Once the string gets to around 20 digits it just returns NaN. Any ideas on whats happening?

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;
} 
like image 261
Joseph Rimar Avatar asked Feb 21 '26 22:02

Joseph Rimar


1 Answers

The problem is caused by JavaScript's floating point number precision. See How to deal with floating point number precision in JavaScript? for more information.

I have created a jsbin version of your function that shows that the error occurs because you are sending in a floating point number larger than floating point precision can store accurately and then converting that to a string. If you think about the decimal number represented by 1011010110100101001 rather than the binary number, then you will realise that is a very large number.

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

console.log(numString);//"1011010110100101000" notice the missing 1 on the right
like image 59
Jeremy Larter Avatar answered Feb 23 '26 10:02

Jeremy Larter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!