3

JavaScript numbers natively support conversion to binary representations via the Number#toString() method. To perform some operation on the binary representation, I converted the number into its binary representation and later into the number as follows,

Example 1 :

(117).toString(2) => "1110101"

Number("1110101") =>  1110101

Example 2 :

(999999).toString(2) => "11110100001000111111"

//I don't understand this
Number("11110100001000111111") => 11110100001000112000

How does Example 2 work, I expected the result to be 11110100001000111111 but I received 11110100001000112000.

Why does Number("11110100001000111111") return 11110100001000112000?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
codeX
  • 4,842
  • 2
  • 31
  • 36
  • Using `Number()` like that will not parse it as a binary number, it's interpreting it as base 10. What operation are you trying to do on the binary number? You can likely do it without converting to binary. Try looking up JavaScript binary operators. – obermillerk Sep 08 '18 at 19:10

2 Answers2

4

First off, there is no binary number format in JS that gets used when you just write ones and zeros, 1110101 is just one million, one hundred ten thousand, one hundred one, and not 117 in binary.

JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integers between -(2^53 - 1) and 2^53 - 1. In JS this is called Number.MAX_SAFE_INTEGER. If you look at the max int and your number side by side:

9007199254740991
11110100001000111111

It becomes quite apparent, that eleven quintillion, one hundred ten quadrillion, one hundred trillion, one billion, one hundred eleven thousand, one hundred eleven is bigger than the max int, so you are bound to have precision loss.

To get a base 10 integer from a binary number, you can pass parseInt a radix as the second parameter:

console.log(parseInt("11110100001000111111", 2))
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
0

in javascript there is something called as max safe integer and computations for integers above it are weird as you have seen

read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

ashish singh
  • 6,526
  • 2
  • 15
  • 35