Problem with some big numbers in Java Script

This is a strange problem that I am facing. When I pass some large numbers into JS functions (user or built-in), the value automatically increases by 1. For example, see This:

<!DOCTYPE html> <html> <body> <p>Click the button to display an alert box.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { alert(10466511635124471); } </script> </body> </html> 

in the warning, I see 10466511635124472 instead of 10466511635124471 . Can anyone explain this behavior?

I checked this in FF 17.0.10 and Chrome 12.0.742.122 and IE 8.

+6
source share
3 answers

This is due to the nature of IEEE754 double-precision 64-bit floating-point math 1 ( all compatible JavaScript implementations use this form of IEEE arithmetic ) - your number 10 466 511 635 124 471 is greater than the highest positive integer, which is represented as consecutive numbers that account for 2 53 (9 007 199 254 740 992). 64 bits of a number in JavaScript are represented using 1 bit for the sign, 52 bits for the number (the special behavior for exponents is effectively 53 bits of precision) and 11 bits for the exponent, so this is the case.

When your number exceeds this maximum number, it will use a score higher than 1 to represent this, which will reduce the smallest possible representation. With an indicator of two (as represented in your case), the smallest differentiable change in numbers will be two, and since your number is between the two, it will be rounded to the nearest.

JavaScript does not have any arbitrary integer format size , nor does it support anything similar to BigNum (to use the term Java) or arbitrary precision arithmetic. If you want to store large numbers, you will have to use another way to store it, such as strings.

1: I contacted Wikipedia as the actual specification really costs money to get legally / officially - if anyone has a better source, edit it.

+1
source

Javascript does not support large integers. It uses a 64-bit float to store numbers, precision, sign and exponent.

Good practice is to use string representations of these numbers:

 alert("10466511635124471"); 

Pay attention to this JSON answer from the Facebook api graph: All reasonable numbers that will be less than 32-bit integers are still integers, but since facebook users use 64-bit integers as their identifiers, they have been converted to line:

http://graph.facebook.com/cocacola

+2
source

The largest positive number allowed in Javascript is 1.79E + 308.

You took the number (10466511635124471), which is larger than the large + ve number. Maybe this is the reason to get an answer like 10466511635124472.

-1
source

Source: https://habr.com/ru/post/958833/


All Articles