Тома Томов Тома Томов - 1 month ago 5
Javascript Question

Decimal to binary - wrong result

Have a question! Why this code :

let number = 6063311135418901680;
let binary = parseInt(number, 10).toString(2);
console.log(binary);


returns
101010000100101001101010101101001010101010100000110010000000000
and not
0101010000100101001101010101101001010101010100000110010010110000
(which is suppose to be the right answer)? I try to convert decimal to binary but maybe i didn t get the right way.I know there is alot of infomation about numbers, but didn`t find nothing to help me.

Answer
0101010000100101001101010101101001010101010100000110010010110000

can't be represented in a variable of type "number" in Javascript for two reasons:

  • numbers don't hold leading zeros
  • integers greater than MAX_SAFE_INTEGER can't usually be exactly represented

The reason behind those constraints is that numbers are stored as IEEE754 double precision floating point numbers. If you need greater integers, either keep them as string or use a big numbers library.

Comments