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.
Large numbers are the numbers that can hold huge memory and evaluation time is more than exceeds space and time to process. We can deal with large numbers in JavaScript using the data type BigInt. It can hold numbers of large size. It perform arithmetic operations. Consumes huge memory.
The math.js library's BigNumber type can represent real or floating point numbers, and can be used with the library's methods. In the final function I will show it in use.
JavaScript Numbers are Always 64-bit Floating Point Value (aka Fraction/Mantissa) Exponent Sign 52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63)
In JavaScript, the largest possible number that can be stored is 1.7976931348623157e+308, or using Number.MAX_VALUE; Things start to get weird when we try to go beyond this point. I tried running the below code expecting “Infinity”. That did not happen.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With