我想生成1到10之间最多2位小数的随机数,
我目前正在使用下面这个来生成我的数字,
var randomnum = Math.floor(Math.random() * (10.00 - 1.00 + 1.00)) + 1.00;
Run Code Online (Sandbox Code Playgroud)
最后,我想知道如何生成如下数字:
1.66
5.86
8.34
格式为:var randomnum = 然后是代码
旁注:我不记得为什么我之前已经生成了这样的数字,但记得有关Math.random生成数字到8位小数的东西.
感谢您的帮助!:)
Ps:我看过很多关于等待向下或向上生成数字的帖子,并且没有找到想直接生成它们的帖子.
更新:我想要一个数字值而不是一个看起来像数字的字符串
Obs*_*ver 10
你非常接近,你需要的是不使用十进制数作为最小值和最大值.让我们有max = 1000和min = 100,所以在你的Math.floor之后你需要除以100:
var randomnum = Math.floor(Math.random() * (1000 - 100) + 100) / 100;
Run Code Online (Sandbox Code Playgroud)
或者,如果您想使用小数:
var precision = 100; // 2 decimals
var randomnum = Math.floor(Math.random() * (10 * precision - 1 * precision) + 1 * precision) / (1*precision);
Run Code Online (Sandbox Code Playgroud)
将原始随机数乘以10^decimalPlaces,求和,然后除以10^decimalPlaces。例如:
floor(8.885729840652472 * 100) / 100 // 8.88
Run Code Online (Sandbox Code Playgroud)
floor(8.885729840652472 * 100) / 100 // 8.88
Run Code Online (Sandbox Code Playgroud)
根据评论进行编辑:
对于包含的浮点随机函数(使用此答案):
function genRand(min, max, decimalPlaces) {
var rand = Math.random() < 0.5 ? ((1-Math.random()) * (max-min) + min) : (Math.random() * (max-min) + min); // could be min or max or anything in between
var power = Math.pow(10, decimalPlaces);
return Math.floor(rand*power) / power;
}
Run Code Online (Sandbox Code Playgroud)