String to Number conversion fails to give the expected result in javascript

Viewed 152

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?

2 Answers

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))

Related