Javascript code to Generate Random Number C# VB.Net Asp.Net

By definition a Random number is a number usually generated by an Application/Process but the basic thing is, the generated number should be unpredictable. In many cases we need to generate Random Number. All languages provides a Random Method to generate Random Number. Javascript also has no exception. In this article I will describe “How to generate Random Number using Javascript Code”. I am using ASP.Net C# & VB.Net pages for this example but anyone can use this Javascript code example in any HTML pages.

Click here to get Jquery Random Number Generation Script.

Note: Javascript Random Function is Math.random() which returns a floating point number in between 0 and 1. So if you want a number between 1 to 100 then you have to multiply the Random Function return value with 100.

Let’s Do Some Examples:
1. Javascript Random Function returns a floating point number:

document.write("<b>Math.random() Returns:</b> " + Math.random());

2. Generate a Random Number in Between 0 to 100:

document.write("<b>Math.random() Returns Between 1 to 100:</b> " + Math.random() * 100 + "</br>");

3. Generate Integer Random Number:

document.write("<b>Math.random() Returns Round Number Between 1 to 50:</b> " + Math.round(Math.random() * 50));

Note: You can try with Math.ceil(), Math.floor() & explore the difference.

4. Generate a Random Number within a Range values means Min and MAX:

document.write("<b>Math.random() Returns Round Number Between MIN and MAX (10-50):</b> " + Math.round(Math.random() * (Max - Min) + Min));

5. Generate Unique Random Number: (for your exercise)
Those who are familiar with ANSI C programming language, We knew that after using the Randomize keyword we will get automatically Unique Random Number. But in Javascript we have no such option. We need to do it by own. Just first generate a number then push the number into an array. After generating each Random number, check with the Array & if not found then add it. That’s it. I am keeping this blank for your exercise.

Note: Full Code Example is same for both C# & VB.Net

Download Code Example C#        Download Code Example VB.Net

Posted in .Net,, C#, Client, Javascript, VB.Net

Leave a Reply

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