Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript can't render this number correctly: 3494793310847464221

Tags:

javascript

I have an interesting question, I have been doing some work with javascript and a database ID came out as "3494793310847464221", now this is being entered into javascript as a number yet it is using the number as a different value, both when output to an alert and when being passed to another javascript function.

Here is some example code to show the error to its fullest.

<html><head><script language="javascript">alert( 3494793310847464221);
var rar =  3494793310847464221;
alert(rar);
</script></head></html>

This has completly baffeled me and for once google is not my friend...

btw the number is 179 more then the number there...


2 Answers

Your number is larger than the maximum allowed integer value in javascript (2^53). This has previously been covered by What is JavaScript's highest integer value that a Number can go to without losing precision?

like image 77
dave Avatar answered Mar 21 '26 17:03

dave


In JavaScript, all numbers (even integral ones) are stored as IEEE-754 floating-point numbers. However, FPs have limited "precision" (see the Wikipedia article for more info), so your number isn't able to be represented exactly.

You will need to either store your number as a string or use some other "bignum" approach (unfortunately, I don't know of any JS bignum libraries off the top of my head).

Edit: After doing a little digging, it doesn't seem as if there's been a lot of work done in the way of JavaScript bignum libraries. In fact, the only bignum implementation of any kind that I was able to find is Edward Martin's JavaScript High Precision Calculator.

like image 28
Ben Blank Avatar answered Mar 21 '26 18:03

Ben Blank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!