Random number generator, breaks for small numbers

Here is my code:

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

The goal is to get random numbers in a given range and round the result to a given decimal place. It works great for ranges like 1-10 or 50-100, but when I try a small number, for example:

randomNumber(0.01,0.05,5)

I get bad results like 0.27335 and 1.04333.

+3
source share
2 answers

You have a reluctant +1 according to your estimates. Must be to-fromwithout +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;
};

Your code should be as follows:

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

Actually, it can be shortened by omitting the variable resultas follows:

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.
};
+2
source
   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;
}
+1
source

All Articles