Having an issue with large integer addition in JavaScript

39 views Asked by At

I'm just making a very simple program to convert binary numbers to decimal and vice versa. In doing the decimal to binary conversion, I realized I was running across a weird error when I try and add a small number to a very large number. For example, I would give my program input 220002 as a decimal and it would convert that number to the binary number 110101101101100020. In debugging this, I realized at the very end it did 110101101101100000 + 10 , and the result was 110101101101100020.

I'm so confused as to why this happened. I'm not really sure, help would be appreciated. It also did it with smaller numbers, such as sometimes it would do a large number in binary form + 1 it would not change the binary number at all. Here is my code if it helps.

$("#convertDecimalBinary").on("click", function() {
    var decimal = $("#inputDecimal").val();
    console.log(!isNaN(decimal));
    if(!isNaN(decimal)) {
      var binary = 0;
      var multiplier = 1;
      var num = 1;
      while(num * 2 <= decimal) {
        num *= 2;
        multiplier *= 10;
      }
      while(decimal > 0) {
        if(decimal - num >= 0) {
          decimal -= num;
          binary += multiplier;
        }
        num /= 2;
        multiplier /= 10;
      }
      $("#inputBinary").val(binary);
    }
  })
1

There are 1 answers

0
ASDFGerte On BEST ANSWER

See float64, This gives 15–17 significant decimal digits precision.. Your number has 18 digits.