Convert exponential number to a whole number in ja

2019-02-25 11:23发布

问题:

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 ?

回答1:

JavaScript 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 become 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 compute 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.



回答2:

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.



回答3:

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.



回答4:

Make the number in two parts and combine 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;