Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with some big numbers in Java Script

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.

like image 457
Hari_639 Avatar asked Nov 26 '13 06:11

Hari_639


People also ask

How to deal with large numbers in JavaScript?

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.

What is a bignumber in JavaScript?

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.

How many bits are in a JavaScript number?

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)

What is the largest possible number that can be stored in JavaScript?

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.


1 Answers

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

like image 155
DhruvPathak Avatar answered Sep 28 '22 04:09

DhruvPathak