Тома Томов Тома Томов - 10 months ago 51
Javascript Question

Decimal to binary - wrong result

Have a question! Why this code :

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

and not
(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 Source

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.