3

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;
} 
Joseph Rimar
  • 81
  • 1
  • 8
  • _"1011010110100101001 returns 372008 instead of 372009"_ - Nope -> http://jsfiddle.net/g3dkyyb9/ – Andreas Jul 17 '15 at 06:33
  • @Andreas The reason your jsfiddle works is because you are calling `binaryConverter2("1011010110100101001")` with a string parameter instead of calling it with a number like this: `binaryConverter2(1011010110100101001)` – Jeremy Larter Jul 17 '15 at 13:03
  • But you said that the function "converts a binary number string to decimal." `binaryConverter2("1011010110100101001")` passes a binary number string. `binaryConverters2(1011010110100101001)` passes a decimal number. – Raymond Chen Jul 18 '15 at 06:48
  • `var numString = num.toString()` only makes sense if `num` is not a string in the first place. So we can deduce that the OP is calling the function with numbers. – Jeremy Larter Jul 18 '15 at 15:34
  • @Jeremy and Raymond. You're both correct. I actually wrote two versions of this function, the first takes a string as the parameter and the second a decimal number. My question pertained to the second function (which is why it's named binaryConverter2) and I mistakenly described it as taking a string instead of converting a decimal number to a string and then another decimal number that represents a binary. – Joseph Rimar Jul 20 '15 at 05:16
  • @Jeremy Thanks for your response. It definitely cleared things up. – Joseph Rimar Jul 20 '15 at 05:18
  • Glad I could help. Is your question answered now, or do you need more clarification? – Jeremy Larter Jul 21 '15 at 21:51

1 Answers1

1

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
Community
  • 1
  • 1
Jeremy Larter
  • 548
  • 2
  • 10
  • 21