Generating Random Numbers in JavaScript

6 posts Page 1 of 1
Contributors
User avatar
comathi
Coding God
Coding God
Posts: 1242
Joined: Fri Mar 26, 2010 1:59 pm

Hi everyone,

Today, I'll be giving you another quick tutorial (I promise it won't be as long as the last one :lol: ).

This time, we'll be looking at JavaScript, and how you can use scripts to generate random numbers. You can use this, for instance, in a raffle, or possibly selecting random images for a banner by looking at the number that was generated. It's all up to you :)

The JavaScript Math.random() function generates a decimal number (floating point) between 0.0 and 1.0 . Generally, you would want a wider range, so for this tutorial, we'll be multiplying the value by 10 to give us a range of 0.0 to 10.0 .

Also, we'll round up our numbers with the Math.ceil() function, which will bring the range back up to 1-10 (no floating point numbers).

Let's start by opening up Notepad (in Windows) or any other program you might use to edit JavaScript files.

Now, you'll first want to insert an init function, since we'll be declaring variables and using them.
Code: Select all
function init()
{

}
window.onload=init;
Inside the function, we'll insert the line of code we'll be using to generate the number:
Code: Select all
var randnum="";
randnum=Math.ceil( Math.random()*10);
What this does is declare a variable named 'randnum', and then gives it a rounded, random value, which is then multiplied by 10.

That's pretty much it. I hope this will have been of use, enjoy! :D
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

You stole my tutorial lol, ill guess I have to make something else :(
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
User avatar
comathi
Coding God
Coding God
Posts: 1242
Joined: Fri Mar 26, 2010 1:59 pm

Ohh, sorry. I did not know you had already posted that :(
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

I haven't, It was only an idea :)
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
User avatar
comathi
Coding God
Coding God
Posts: 1242
Joined: Fri Mar 26, 2010 1:59 pm

Oh ok. Well sorry anyways. I didn't mean to take your idea.
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

You couldn't know :) Im making a C++ tut instead, and maybe some random numbers in PHP :lol:
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
6 posts Page 1 of 1
Return to “Tutorials”