Skip to content Skip to sidebar Skip to footer

Convert Exponential Number To A Whole Number In Javascript

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()*1111111111111111

Solution 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.

Solution 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.

Solution 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.

Solution 4:

Make the number in two parts and combine them as a string.

var id1 = Math.floor( Math.random() * 10e10 ); // 11 digitsvar id2 = Math.floor( Math.random() * 10e11 ); // 12 digitsvar id = id1+''+id2;

Post a Comment for "Convert Exponential Number To A Whole Number In Javascript"