Reputation: 28492
JavaScript has a limitation in integer precision defined by Number.MAX_SAFE_INTEGER
. Any number that goes beyond this runs the risk of being inaccurate. This is because it cannot be represented accurately in memory due to bit movement as outlined in this answer:
var max = Number.MAX_SAFE_INTEGER;
max + 0; // 9,007,199,254,740,991
max + 1; // 9,007,199,254,740,992
max + 2; // 9,007,199,254,740,992 (!)
max + 3; // 9,007,199,254,740,994
max + 4; // 9,007,199,254,740,996 (!)
// ...
Any result you get above max
is very unreliable, making it almost entirely useless, and prone to leading to bugs if the developer isn't expecting it or aware of this limitation.
My question is, what's the point of having numbers beyond this value? Is there any practical use for JavaScript to allow a Number
beyond this? It can reach Number.MAX_VALUE
(1.79e+308), which is substantially larger than MAX_SAFE_INTEGER
, but everything in between the two values is not very useful, and it forces the developer to switch to BigInt
.
Upvotes: 5
Views: 1165
Reputation: 4097
everything in between the two values is not very useful, and it forces the developer to switch to BigInt.
It can be useful if absolute precision isn't required. When dealing with huge numbers, it's not very usual to require that much.
Take incremental games for an example. They often need to represent huge numbers, but the insignificant tail end of the values (for example, the thousands, when the numbers being dealt with are on the order of 1e20) isn't important and can be safely discarded without impacting functionality.
BigInts are a somewhat new thing too. Before it existed, it was useful to be able represent huge numbers even if they were sometimes slightly inaccurate with their least significant digits. Before BigInts, better to be able to represent huge numbers despite slight inaccuracy than to not be able to represent huge numbers at all.
Upvotes: 3