Тома Томов
Тома Томов

Reputation: 51

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.

Upvotes: 0

Views: 50

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382142

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.

Upvotes: 1

Related Questions