您的计算结果不情愿 +1。应该to-from
没有+1:
var randomNumber = function (from, to, dec) {
var num = Math.random() * (to - from +1) + from;
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
};
您的代码应如下所示:
var randomNumber = function (from, to, dec) {
var num = Math.random() * (to - from) + from;
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
};
实际上,可以通过省略以下result
变量来进一步缩短它:
var randomNumber = function (from, to, dec) {
var num = Math.random() * (to - from) + from; //Generate a random float
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec); //Round it to <dec> digits. Return.
};