3

这是我的代码:

    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;
};

目标是获取给定范围内的随机数并将结果四舍五入到给定的小数位。它适用于 1-10 或 50-100 等范围,但是当我尝试这样的小数字时:

randomNumber(0.01,0.05,5)

我得到像 0.27335 和 1.04333 这样的坏结果。

4

2 回答 2

2

您的计算结果不情愿 +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.
};
于 2012-05-07T11:22:27.743 回答
1
   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;
}
于 2012-05-07T11:29:54.903 回答