JavaScript,生成一个长度为 9 个数字的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3437133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript, Generate a Random Number that is 9 numbers in length
提问by AnApprentice
I'm looking for an efficient, elegant way to generate a JavaScript variable that is 9 digits in length:
我正在寻找一种高效、优雅的方式来生成长度为 9 位的 JavaScript 变量:
Example: 323760488
示例:323760488
回答by ggg
You could generate 9 random digits and concatenate them all together.
您可以生成 9 个随机数字并将它们连接在一起。
Or, you could call random()and multiply the result by 1000000000:
或者,您可以调用random()结果乘以 1000000000:
Math.floor(Math.random() * 1000000000);
Since Math.random()generates a random double precision number between 0 and 1, you will have enough digits of precision to still have randomness in your least significant place.
由于Math.random()生成一个介于 0 和 1 之间的随机双精度数,您将有足够的精度位数,以便在最不重要的地方仍然具有随机性。
If you want to ensure that your number starts with a nonzero digit, try:
如果您想确保您的号码以非零数字开头,请尝试:
Math.floor(100000000 + Math.random() * 900000000);
Or pad with zeros:
或者用零填充:
function LeftPadWithZeros(number, length)
{
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Or pad using this inline 'trick'.
或使用此内联 'trick' 进行填充。
回答by mykhal
why don't just extract digits from the Math.random()string representation?
为什么不从Math.random()字符串表示中提取数字?
Math.random().toString().slice(2,11);
/*
Math.random() -> 0.12345678901234
.toString() -> "0.12345678901234"
.slice(2,11) -> "123456789"
*/
(requirement is that every javascript implementation Math.random()'s precision is at least 9 decimal places)
(要求每个 javascript 实现Math.random()的精度至少为 9 位小数)
回答by José
Also...
还...
function getRandom(length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * 9 * Math.pow(10, length-1));
}
getRandom(9) => 234664534
getRandom(9) => 234664534
回答by Johnny Leung
Three methods I've found in order of efficiency: (Test machine running Firefox 7.0 Win XP)
我找到的三种方法按效率排序:(测试机器运行Firefox 7.0 Win XP)
parseInt(Math.random()*1000000000, 10)
1 million iterations: ~626ms. By far the fastest - parseInt is a native function vs calling the Math library again. NOTE: See below.
100 万次迭代:~626 毫秒。迄今为止最快的 - parseInt 是一个本机函数,而不是再次调用 Math 库。注意:见下文。
Math.floor(Math.random()*1000000000)
1 million iterations: ~1005ms. Two function calls.
100 万次迭代:~1005 毫秒。两个函数调用。
String(Math.random()).substring(2,11)
1 million iterations: ~2997ms. Three function calls.
100 万次迭代:~2997 毫秒。三个函数调用。
And also...
并且...
parseInt(Math.random()*1000000000)
1 million iterations: ~362ms. NOTE: parseInt is usually noted as unsafe to use without radix parameter. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseIntor google "JavaScript: The Good Parts". However, it seems the parameter passed to parseInt will never begin with '0' or '0x' since the input is first multiplied by 1000000000. YMMV.
100 万次迭代:~362 毫秒。注意: parseInt 通常被认为在没有基数参数的情况下使用是不安全的。请参阅https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt或谷歌“JavaScript: The Good Parts”。但是,似乎传递给 parseInt 的参数永远不会以“0”或“0x”开头,因为输入首先乘以 1000000000。YMMV。
回答by cespon
In one line(ish):
在一行中(ish):
var len = 10;
parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);
Steps:
脚步:
- We generate a random number that fulfil
1 ≤ x < 10. - Then, we multiply by
Math.pow(10,len-1)(number with a lengthlen). - Finally,
parseInt()to remove decimals.
- 我们生成一个满足 的随机数
1 ≤ x < 10。 - 然后,我们乘以
Math.pow(10,len-1)(具有长度的数字len)。 - 最后,
parseInt()去除小数点。
回答by nvitaterna
Math.random().toFixed(length).split('.')[1]
Using toFixed alows you to set the length longer than the default (seems to generate 15-16 digits after the decimal. ToFixed will let you get more digits if you need them.
使用 toFixed 允许您设置比默认值更长的长度(似乎在小数点后生成 15-16 位数字。如果需要,ToFixed 将让您获得更多数字。
回答by Katie Mary
Thought I would take a stab at your question. When I ran the following code it worked for me.
以为我会刺伤你的问题。当我运行以下代码时,它对我有用。
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
} //The maximum is exclusive and the minimum is inclusive
$(document).ready(function() {
$("#random-button").on("click", function() {
var randomNumber = getRandomInt(100000000, 999999999);
$("#random-number").html(randomNumber);
});
</script>
回答by JohnB
回答by PrenticeRealty
function rand(len){var x='';
for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
return x;
}
rand(9);
回答by Emeeus
I know the answer is old, but I want to share this way to generate integers or float numbers from 0 to n. Note that the position of the point (float case) is random between the boundaries. The number is an string because the limitation of the MAX_SAFE_INTEGERthat is now 9007199254740991
我知道答案很旧,但我想分享这种方式来生成从 0 到 n 的整数或浮点数。请注意,点(浮动情况)的位置在边界之间是随机的。该数字是一个字符串,因为现在 9007199254740991的MAX_SAFE_INTEGER的限制
Math.hRandom = function(positions, float = false) {
var number = "";
var point = -1;
if (float) point = Math.floor(Math.random() * positions) + 1;
for (let i = 0; i < positions; i++) {
if (i == point) number += ".";
number += Math.floor(Math.random() * 10);
}
return number;
}
//integer random number 9 numbers
console.log(Math.hRandom(9));
//float random number from 0 to 9e1000 with 1000 numbers.
console.log(Math.hRandom(1000, true));

