Generate a Random Number

The Rnd function returns a value less than 1 but greater than or equal to 0.
Note that to use the Rnd function properly you must place the Randomize statement somewhere before it to ensure that a new random number is generated each time the page is reloaded. Have a look at the following code in Example 1.

Example 1;

<%
Dim MyRandomNum
Randomize
MyRandomNum = Rnd
Response.Write MyRandomNum
%>

The above code will produce a different number each time. Below are typical numbers produced.
0.9923431
0.2924431

Example 2 below shows the code to create a number between 1-100.

Example 2;

<%
Dim MyNewRandomNum
Randomize
MyNewRandomNum = (Rnd * 100)+1
response.write MyNewRandomNum
%>

The code above will produce a number such as 55.9393933
To get rid of the decimals we can use the Int function as in example 3 below.

Example 3;

<%
Dim MyNewRandomNum
Randomize
MyNewRandomNum = Int(Rnd * 100)+1
response.write MyNewRandomNum
%>

The above code chops off the decimals and leaves you with a number such as 55.
Note that it doesn't round the number of, it merely chops off the decimals.
To round of the number use the Round function instead of Int as is demonstrated in example 4 below.

Example 4;

<%
Dim MyNewRandomNum
Randomize
MyNewRandomNum = Round(Rnd * 100)+1
response.write MyNewRandomNum
%>

Related tutorial 'Generate a random number between 2 numbers'
Here's the code to display a random quote

Get the best asp web hosting provider now and save 30%

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.