13

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?

5 Answers 5

17

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
Sign up to request clarification or add additional context in comments.

Comments

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?

1 Comment

I do numeric operation. I actualy create my own library and I want create Int64 class like C#
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

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.