9

I have worked the same process in JavaScript with number datatype

var num = 9223372036854775807;

But when I try print this variable in browser

alert(num)

the value changed to 9223372036854776000

Any ideas?

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
developerone
  • 141
  • 1
  • 3

5 Answers5

15

Javascript numbers are actually double precision floats. The largest integer that can be precisely stored is 253, much less then your 263-1.

alert( Math.pow(2, 53) - 1 ) // 9007199254740991
alert( Math.pow(2, 53)     ) // 9007199254740992
alert( Math.pow(2, 53) + 1 ) // 9007199254740992
hugomg
  • 68,213
  • 24
  • 160
  • 246
2

Javascript stores longs as javascript numbers (64 bit floats). And 9223372036854776000 is MAX.

Do you do numeric operations or can you store it as a string?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Eystein Bye
  • 5,016
  • 2
  • 20
  • 18
1

Because the maximum integer value of a number in js is 9007199254740992. See What is JavaScript's highest integer value that a Number can go to without losing precision? for more

Community
  • 1
  • 1
Geuis
  • 41,122
  • 56
  • 157
  • 219
0

alert(9223372036854775807n)

What did I do?

I just placed a "n" at the end the of the number

Why did it work?

JavaScript stores numbers as 53 bits. BigInt can be used to work with larger numbers. So that's what I used. ##Conclusion## for big numbers that must always be correct to the nearest digit, use BigInt.

Sive
  • 79
  • 11
0

The problem is exactly as described by @missingno, probably the best solution, if you really need to handle big numbers is the BigNumber Class: http://jsfromhell.com/classes/bignumber

It is worth noting that this is not going to be an efficient way to do calculations compared with other languages, but it is probably the easiest to manage in JavaScript.

Billy Moon
  • 57,113
  • 24
  • 136
  • 237