# Quick Tip: Get a Random Number Within a Specified Range Using AS3

This entry is part 1 of 13 in the You Do The Math Session
Next »

We often need to use a randomly generated number for certain situations; using Math.random() * n will usually do the trick, but it will only calculate a number from 0 to n. What if we need a number that doesn’t give 0 as the minimum value? How can you generate a random number between 100 and 1000? I’ll show you how to do it in this Quick Tip.

## Final Result

This example demonstrates the function we’ll be creating:

Input two numbers separated by a ‘,’ and press the random button.

## Step 1: Brief Overview

Using a function created in ActionScript 3, we will calculate a number between two values. These values will be passed as parameters and used with the Math class to generate a random number.

## Step 2: Create a New File

Open Flash and create a new Flash File (ActionScript 3.0).

## Step 3: Open the Actions Panel

Press Option + F9 or go to Window > Actions to open the Actions Panel.

## Step 4: Function Declaration

Declare a Function and name it randomRange; this function will return the random number, so set the return type to Number.

function randomRange():Number
{

## Step 5: Set Parameters

Two parameters will be used to calculate the number.

• minNum: The minimum value to return
• maxNum: The maximum value to return
function randomRange(minNum:Number, maxNum:Number):Number
{

## Step 6: Write the Main Function

This is the function with the actual random number generator line. The power of Math is used to generate the number.

function randomRange(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}

## Step 7: How it Works

We have our random number generator function, but what does this function do?

Take a look at the following image to get a better idea:

In the image’s example, if Math.random() was less than 0.5, the result would be 550.

## Step 8: Test with a Trace

A simple way to test the function is to use a trace() function. See the code below:

function randomRange(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}

trace(randomRange(10, 20)); //A number between 10 and 20

## Step 9: Example

This is a working example, it uses a button to calculate the number and display it in a TextField.

/* The randomRange function */

function randomRange(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}

/* The actions that will perform when the button is pressed */

function buttonAction(e:MouseEvent):void
{
//An array will store the numbers in the textfield
var n:Array = inputText.text.split(",");

//Calculate the number based on the input, convert the result to a string
//and send that string to the textfield
generatedNumber.text = String(randomRange(n[0], n[1]));
}

actionButton.addEventListener(MouseEvent.MOUSE_UP, buttonAction); 

Input two numbers separated by a ‘,’ and press the random button.

## Conclusion

This is a basic example of how you can use this function; experiment and use it in your own projects!

Tags: Tips
• http://www.criaideias.com.br/english.hmtl Gustavo Guichard

I think it’s easier using:
return (Math.ceil(Math.random() * (maxNum – minNum)) + minNum);
Using the Math.ceil method, you don’t need the “+1″.
What do you think about it?

• http://www.criaideias.com.br/english.hmtl Gustavo Guichard

Easier way to do it:
return (Math.ceil(Math.random() * (maxNum – minNum)) + minNum);
Then you don’t have to use the “+1″

• Ben

@Gustavo

The reason ceiling doesnt work is because Math.random() can return 0. Ceiling on 0 won’t work with this function.

• http://www.criaideias.com.br/english.hmtl Gustavo Guichard

I’ve been trying to comment, but I’m always getting the “Connection Timeout”…
Let’s just try again!:

More semantic way to do it:
return (Math.ceil(Math.random() * (maxNum – minNum)) + minNum);

Using the Math.ceil you don’t have to use the “+1″

• Ben

@Gustavo

The reason ceiling doesnt work is because Math.random() can return 0. Ceiling on 0 won’t work with this function.­­“

• http://cjcat.blogspot.com Allen Chou

Just a quick tip: int() is much faster than Math.floor().
So you can replace Math.floor(x) with int(x), Math.ceil(x) with int(x + 1), and Math.round(x) with int(x + 0.5).

• http://cjcat.blogspot.com Allen Chou

Oh, by the way, do not wrap this formula into functions. The function call overhead cancels out the performance gain, sometimes even yielding worse performance. Instead, use the int() function directly at wherever it is needed.

I keep a file with a function like this in my class path.
Then I can just import it into any project that needs it (which is pretty much every project).

• André

I keep a MathTool class with some functions in the root of my class path, one of them is MathTool.random(value1,value2)

But it returns… minNum+(Math.random()*(maxNum-minNum));

if floatNumber parameter is set to false it returns the Math.floor of this number, always worked

• l’homme collectif

great tutorial thanks

• Luka

Tnx for tutorial

Luka

• sash

Doesn’t work for a range like [0.1 , 0.9]

• http://michaeljameswilliams.com/ Michael James Williams

True. Perhaps this should have been titled, “Get a Random Integer Within a Specified Range”.

• marek

Use range [1, 9] then divide by 10.

• Rob

hello, how to make range beetwen 4 numbers like this
50-250 and 275-500 ??