# Givaway! True random range function

**URL:** <https://forum.kirupa.com/t/givaway-true-random-range-function/282669>\
**Category:** Uncategorized\
**Created:** [February 24, 2009, 11:54pm UTC](https://forum.kirupa.com/t/givaway-true-random-range-function/282669 "2009-02-24T23:54:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![nook](https://avatars.discourse-cdn.com/v4/letter/n/90ced4/32.png) [@nook](https://forum.kirupa.com/u/nook)\
**Post date:** [February 24, 2009, 11:54pm UTC](https://forum.kirupa.com/t/givaway-true-random-range-function/282669/1 "2009-02-24T23:54:19Z")

</div>

Maybe some of you have something similar alreay but since I’ve been flashing for more than 5 years and have never before realised I was missing this until I made it, I’m figuring quite a few would benefit from it.

As you know the Math.random function in flash generates:  
0 \<= n \< 1.

When you want a random integer from 0 to n you might do like this:  
`Math.round(Math.random() * n);`

This indeed generates a number between and including 0 and n, but 0 and n will appear less often since they only have half the rounding span compared to the values in between.

So we use floor instead like this:  
`Math.floor(Math.random() * (n+1));`

This will give us a value between and including 0 and n with equal chance.  
To get a value from n1 to n2 you write:  
`Math.floor(Math.random() * (n2-n1+1)) + n1;`

Now. What if we want a float between and including 0 and n, or n1 and n2?  
This was the idea that got me to write this function:

```auto

function randomRange(min:Number, max:Number, nrOfDecimals:int=2):Number {
 
var randomVal:Number = Math.random() * (max-min + Math.pow(10, -nrOfDecimals)) + min;
 
var returnVal:Number = int(randomVal * Math.pow(10, nrOfDecimals)) / Math.pow(10, nrOfDecimals);
 
return returnVal;
}

```

If you want integers you simply pass 0 as the argument for “nrOfDecimals”.  
This has come in handy for me working with objects that has a lot of properties set with min and max random values. And for positioning graphics you really don’t need more than 2 decimals for floating values.

cheers :: nook

[SIZE=1]ps Couldn’t get “[as2]”-tag to work?? ds[/SIZE]
