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 within a given range and round the result to a given decimal place. It works fine for ranges like 1-10 or 50-100, but when I try a small number like so:
randomNumber(0.01,0.05,5)
I get bad results like 0.27335 and 1.04333.
You have a reluctant +1 on your calculation. Should be
to-fromwithout the +1:Your code should be as follows:
Actually, it can be further shortened by omitting the
resultvariable as follows: