Convert exponential number to a whole number in javascript

后端 未结 4 1441
执念已碎
执念已碎 2021-01-20 18:17

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 =          


        
相关标签:
4条回答
  • 2021-01-20 18:49

    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.

    0 讨论(0)
  • 2021-01-20 19:06

    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.

    0 讨论(0)
  • 2021-01-20 19:08

    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;
    
    0 讨论(0)
  • 2021-01-20 19:11

    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.

    0 讨论(0)
提交回复
热议问题