0

i'm not expert in decimal to binary conversion. For my current project i have to develop a tool for decimal to binary conversion. Luckily i found the code on stackoverflow for the conversion. But, when i add more then 16 numbers, i get wrong answer. I checked a few tools and all tools are showing different answers but their answers are close to one another. i need help. My answers are nowhere near to the answers shown by the following tools.

https://binarytotext.net/decimal-to-binary/ & https://www.rapidtables.com/convert/number/decimal-to-binary.html https://www.binaryhexconverter.com/decimal-to-binary-converter

I would appreciate any help.

The code i found on stackoverflow:

var xx = document.getElementById("input").value;
var xy = parseInt(xx);
  var xz = xy.toString(2);
    document.getElementById("demo").innerHTML = xz;

  • What is the initial value of `xx`, what do you expect it to be, and what is the actual value after you have converted it? – old greg Dec 22 '20 at 11:28
  • XX is the value coming from user input. This code returns correct answer until I insert a value which is greater then 16 characters. For example, if I insert "1111111111111111111111" then the correct answer(according to the tool) is 1111000011101111000011101001001010001011110111010111000111000111000111. And my tool returns "1111000011101111000011101001001010001011110111010111000000000000000000". There are no similarities between these two answers – Denzel Vieta Dec 22 '20 at 11:37
  • They are using bignumber.js. Javascript is not great when you have to deal with numbers. I faced the same issue with numbers a long ago. Try bignumber, have a look at this thread: https://stackoverflow.com/questions/4288821/how-to-deal-with-big-numbers-in-javascript – brhyan_baker Dec 22 '20 at 11:30
  • see: [Number.MAX_SAFE_INTEGER](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). The longest safe integer is `9007199254740991` (which is 16 digits long) You'll need to use [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) beyond that. – pilchard Dec 22 '20 at 13:34

0 Answers0