I am in need use 23 digit number in a url. I am generating number using Math.random() but I get the result in exponential form.
My code is
var id = (Math.random()*11111111111111111111111).toFixed(23);
but I got result as 6.286119436349295e+21
how to store random value in "id" as a whole number ?
I am in need use 23 digit number in a url. I am generating number using Math.random() but I get the result in exponential form.
My code is
var id = (Math.random()*11111111111111111111111).toFixed(23);
but I got result as 6.286119436349295e+21
how to store random value in "id" as a whole number ?
Share Improve this question edited Dec 26, 2012 at 8:02 Vishal Suthar 17.2k4 gold badges63 silver badges108 bronze badges asked Dec 26, 2012 at 8:00 GowsikanGowsikan 5,7019 gold badges35 silver badges44 bronze badges 1- 'digit', that's a decimal digit, I presume? – xtofl Commented Dec 26, 2012 at 8:03
4 Answers
Reset to default 2JavaScript can represent contiguously the integers between -9007199254740992 and 9007199254740992. It actually can represent larger (and smaller) integers, but not all of them! In fact the "next" integer after 9007199254740992 is 9007199254740994. They are two apart for a while, then bee 4 apart, then 8, etc. As you noticed, when they get really large, they display in scientific notation. Even the result of toFixed
is not guaranteed to be displayed in a form that consists of digits only.
So when you pute integers that would be in the range of 23 decimal digits, you would be unable to represent a bunch of them using JavaScript's native Number
type (IEEE-754 64-bit).
If you don't care about a specific distribution for your random numbers, a random string over the alphabet 0..9
can work, as can pasting together smaller integers, but if you are looking for a specific distribution then you should (as suggested by Ignacio Vasquez-Abrams) use a library supporting arbitrary-length precision.
JavaScript numbers are not precise enough for that. You will never be able to get full 23 random digits. It would be easier getting a several smaller numbers and pasting them together as a string.
You can't; it won't fit in even a 64-bit integer, much less a 32-bit integer. Use an arbitrary-length integer library.
Make the number in two parts and bine them as a string.
var id1 = Math.floor( Math.random() * 10e10 ); // 11 digits
var id2 = Math.floor( Math.random() * 10e11 ); // 12 digits
var id = id1+''+id2;