Here’s my little function to return a random number between two numbers:
1 2 3 4 5 6 7 8 9 |
function randomNumberBetween(from, to, allowZero){ var diff=(to+1)-from; var rnum = Math.floor((Math.random() * diff)); rnum+=from; if(rnum==0 && allowZero===false){ rnum=from==0?1:from; // just make it easy for now } return rnum; } |
The ‘allowZero’ flag does just that.. though if you use this function you may wish to change what it does if it does generate a zero.
It’ll work on negative to positive numbers, but if you want decimal numbers (i.e. 0.0 to 1.0) you would need to do between 1 and 10, and then divide by 10 to get your result.