Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parseInt returning values that differs by 1 [duplicate]

Tags:

javascript

I have data like this:

var currentValue="12345678901234561";

and I'm trying to parse it:

var number = parseInt(currentValue, 10) || 0;

and my result is:

number = 12345678901234560

now lets try:

currentValue="12345678901234567"

in this case parseInt(currentValue,10) will result in 12345678901234568

Can anyone explain me why parseInt is adding/substracting 1 from values provided by me?

like image 658
szpic Avatar asked Feb 09 '23 18:02

szpic


1 Answers

Can anyone explain me why parseInt is adding/substracting 1 from values provided by me?

It's not, quite, but JavaScript numbers are IEEE-754 double-precision binary floating point (even when you're using parseInt), which have only about 15 digits of precision. Your number is 17 digits long, so precision suffers, and the lowest-order digits get spongy.

The maximum reliable integer value is 9,007,199,254,740,991, which is available from the property Number.MAX_SAFE_INTEGER on modern JavaScript engines. (Similarly, there's Number.MIN_SAFE_INTEGER, which is -9,007,199,254,740,991.)

Some integer-specific operations, like the bitwise operators ~, &, and |, convert their floating-point number operands to signed 32-bit integers, which gives us a much smaller range: -231 (-2,147,483,648) through 231-1 (2,147,483,647). Others, like <<, >>, and >>>, convert it to an unsigned 32-bit integer, giving us the range 0 through 4,294,967,295. Finally, just to round out our integer discussion, the length of an array is always a number within the unsigned 32-bit integer range.

like image 100
T.J. Crowder Avatar answered Feb 11 '23 07:02

T.J. Crowder