admin管理员组文章数量:1400174
I know that I need to use Math.random() for making random numbers, but today I tried to make a random number between 1 and 9999...(9 repeated 19 times) and my output always ends in 3-5 zeroes. How can I generate more detailed random numbers?
What I've done:
const foo = Math.floor(Math.random() * parseInt("9".repeat(19)));
Also, I'm pretty sure I know how to do this, but if anyone can tell me, how do I pad zeroes to get to a certain digit count? (ex. pad(15,4) bees 0015 because the you need 2 more digits to make it 4 digits long)
I know that I need to use Math.random() for making random numbers, but today I tried to make a random number between 1 and 9999...(9 repeated 19 times) and my output always ends in 3-5 zeroes. How can I generate more detailed random numbers?
What I've done:
const foo = Math.floor(Math.random() * parseInt("9".repeat(19)));
Also, I'm pretty sure I know how to do this, but if anyone can tell me, how do I pad zeroes to get to a certain digit count? (ex. pad(15,4) bees 0015 because the you need 2 more digits to make it 4 digits long)
Share Improve this question asked Jan 28, 2019 at 22:48 DexieTheSheepDexieTheSheep 4601 gold badge7 silver badges16 bronze badges 3-
7
The maximum integer you can represent without loss of precision is
2^53 - 1
, which has 16 digits. In other words, you cannot have an integer value derived from a 19 digit long string without loosing precision. Proof:9007199254740991 + 1
and9007199254740991 + 2
are both9007199254740992
. Wele to the world of floating point values. – Felix Kling Commented Jan 28, 2019 at 22:53 -
1
So, what you may want is
Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
instead. – Felix Kling Commented Jan 28, 2019 at 22:57 -
padStart
– Bergi Commented Jan 28, 2019 at 22:58
3 Answers
Reset to default 3The best idea is probably to just use a string of random integers (solves padding too):
let foo = '';
for(i=0; i<19; ++i) foo += Math.floor(Math.random() * 10);
alert(foo);
You are running into Number.MAX_SAFE_INTEGER. The largest exact integral value is 2^53-1, or 9007199254740991.
You need to use numbers encoded as strings. A loop like this:
var desiredMaxLength = 19
var randomNumber = '';
for (var i = 0; i < desiredMaxLength; i++) {
randomNumber += Math.floor(Math.random() * 10);
}
Arthimetic for numbers represented as strings can be donw with the strint
library found at https://github./rauschma/strint.
本文标签: javascriptJSHow can I generate a long random numberStack Overflow
版权声明:本文标题:javascript - JS - How can I generate a long random number? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744248904a2597154.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论