Convert exponential number to a whole number in javascript

后端 未结 4 1444
执念已碎
执念已碎 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题