2009
14
Jun

JavaScript Random Between Function

Generally random number functions pick a number between 0 and another number. Every couple of months I run into a case where I need to pick a random number between two numbers. For example I need a random number between 5 and 10. I always seems to have a tough time finding one online for some reason so I am posting this in the hopes it will help someone else or even me when I need to use it again later.

This function also allows you to specify the decimal places for your random number.

function randomBetween(minV, maxV, floatV)<br>{<br>	var randV = minV + (Math.random() * (maxV - minV));<br>	return typeof floatV == 'undefined' ? Math.round(randV) : rand.toFixed(floatV);<br>}

You can use something similar with Flash as well. I have a class that extends the Math class but I haven’t uploaded it yet.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>