Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript parseInt conversion is buggy [duplicate]

Tags:

javascript

When running

   console.log(parseInt("9658921879781125"))
it gives a value of 9658921879781124, which is less than the original value.

Why is this the case?

like image 365
Manoj Sureddi Avatar asked Dec 14 '17 10:12

Manoj Sureddi


1 Answers

That would be because

9658921879781125 > Number.MAX_SAFE_INTEGER // true

So it is unsafe to try to work with numbers greater than Number.MAX_SAFE_INTEGER


The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(253 - 1) and 253 - 1.

Safe in this context refers to the ability to represent integers exactly and to correctly compare them.

like image 95
Gabriele Petrioli Avatar answered Nov 14 '22 05:11

Gabriele Petrioli