Ziba Leah - 6 days ago 5
Javascript Question

# Why does this number get increased by one?

``console.log(10209761399365907);``

Why does this code output a number greater by one (10209761399365908 instead of 10209761399365907)?

This is happening only for this specific number. For instance with 10155071933693662 I get the correct value (10155071933693662).

Is there something I need to know about that specific number? The only workaround I figured out is to pass the value as a string.

Answer

Your numeric value is too large to be represented exactly as a 64-bit floating point number. The value you get is an approximation. JavaScript natively only has 64-bit floating point numbers; values that do fit in a `long` in C or C++ may be too large to be represented exactly, because some of the 64 bits are used for an exponent in floating point representation. (The trade off is that with floating point it's possible to work with approximations for values with much larger or smaller numeric magnitude than is possible with simple integer representation.)

If it's not important to manipulate the value as a number, make it a string:

``````<input type="button" value="Invita" onclick="Invite('@us.FacebookID')" />
``````

There's a constant (in newer JavaScript environments) called `Number.MAX_SAFE_INTEGER`. That tells you how big a number you can represent such that the value will be represented exactly; that is, that the 64-bit floating point mantissa will contain explicit bits for the entire value.

Larger even integers can be represented exactly, depending on how many zero bits are at the low end of their binary representation. Thus, `1152921504606846800` can be exactly represented, because it's got 7 bits of all zeros at the low end of the binary representation. However, `1152921504606846801` comes out as `1152921504606846800` because that low `1` bit has nowhere to go. (Unrepresented bits are assumed to be zero.)

Source (Stackoverflow)
Comments