Question

This is a strange issue I'm facing. When I pass some big numbers to JS functions (custom or built-in) the value is automatically getting incremented 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 alert I'm seeing 10466511635124472, instead of 10466511635124471. Can someone explain this behavior?

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

Was it helpful?

Solution 2

This is to do with the nature of IEEE754 double-precision 64-bit floating point math1 (all compliant JavaScript implementations use this form of IEEE arithmetic) -- your number 10 466 511 635 124 471 is larger than the highest positive integer that is representable as consecutive numbers, which is 253 (9 007 199 254 740 992). The 64 bits of a number in JavaScript are represented using 1 bit for the sign, 52 bits for the number (special behaviour for exponents effectively make 53 bits of precision) and 11 bits for the exponent, which is why that's the case.

When your number exceeds this maximum number, it will use an exponent of higher than 1 to represent this, which will result in the smallest possible representation lowering. With an exponent of two (as it is represented in your case), the smallest differentiable change in numbers will be two, and because your number is between these two, it will be rounded to the nearest one.

JavaScript does not have any arbitrary-size integer format, nor does it have support for anything similar to BigNum (to use the Java term) or arbitrary-precision arithmetic. If you'd like to store larger numbers, you'd have to use some other method of storing it, such as strings.

1: I've linked to Wikipedia as the actual specification does cost money to obtain legally/officially -- if someone has a better source please edit it in.

OTHER TIPS

Javascript does not have any support for big integers. It uses 64 bit float to store the number,precision,sign and exponent.

A good practice is to use string representations of these numbers :

alert("10466511635124471");

Notice this JSON response from Facebook graph api : All the reasonably numbers which would be smaller than 32 bit integers are still integers, but as facebook users 64 bit integers as its ids, they have been converted to strings :

http://graph.facebook.com/cocacola

Largest positive number allowed in Javascript is 1.79E+308.

You have taken a number(10466511635124471), which is greater than the larget +ve number.May be this is the reason to get the answer as 10466511635124472.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top