随机数生成器,中断小数

时间:2012-05-07 11:08:59

标签: javascript

这是我的代码:

    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。

2 个答案:

答案 0 :(得分: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.
};

答案 1 :(得分: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;
}