Converting string to number produces incremented value:
var n = '9999999999999999';
console.log(n); // -> 9999999999999999
var nn = Number(n)
console.log(nn); // -> 10000000000000000
How to avoid this?
Converting string to number produces incremented value:
var n = '9999999999999999';
console.log(n); // -> 9999999999999999
var nn = Number(n)
console.log(nn); // -> 10000000000000000
How to avoid this?
9999999999999999
is treated internally in JavaScript as a floating-point number. It cannot be accurately represented in IEEE 754 double precision as it would require 54 bits of precision (the number of bits is log2(9999999999999999)
= 53.150849512 and since fractional bits do not exist, the result must be rouned up) while IEEE 754 provides only 53 bits (1 implict bit + 52 explicitly stored bits of the mantissa) - one bit less. Hence the number simply gets rounded.
Since only one bit is lost in this case, even 54-bit numbers are exactly representable, since they nevertheless contain 0 in the bit, which gets lost. Odd 54-bit numbers are rounded to the nearest value that happens to be a doubled even 53-bit number given the default unbiased rounding mode of IEEE 754.