'CSS Tutorials'

The Beauty of Random Numbering with JavaScript

19 NOV 2010 4

Hello again!

This is a bit nerdy, but a very cool thing you can do is to play with javascript and random numbers and the math functions (this is nerdy, all right).

First, we need the functions we will work with:  math.floor() and math.random()

- math.floor() - Rounds the number down to its smallest point, so 4.9 becomes 4, 5.3 becomes 5 and so on and so forth

- math.random() - Returns a number between 0 and 1

How can we use them both together? Very easily:

// random number between 0 and 10 //
// the * 11 part is the max number you can roll, you put 11 because 0.9 x 11 is less than 11 so it will be
// rounded down to 10,
 $(document).ready(function(){
 var x = Math.floor(Math.random() * 11);
 $("body").append("<div class='alpha'> </div>");
 $(".alpha").text(x);
});

The above code will give you numbers between 0 (including 0) and 10 (including 10).

If you want to skip the 0, and actually get numbers between 1 to 10, then you need to do this:

// however you can get also a 0 number because 0.0(something) will be rounded to 0
// in order to prevent that we add a +1 like this. this means that you will have numbers between 1 and 11
// so we have to make it * 10 instead of * 11
 $(document).ready(function(){
 var x = Math.floor(Math.random() * 10)  + 1;
 $("body").append("<div class='alpha'> </div>");
 $(".alpha").text(x);
});

The reason why I changed it to *10 is because 0.9 x 10 = 9 and adding 1 at the end of the function will bring it to 10, however 0.0 x 10 = 0 + 1 = 1, so we will never ever get a 0.

Of course, you can change the numbers to suit your needs.

This technique is very useful when you try to do random numbering or random encryption.

You can easily do a full number password generator just by combining the function 10-15 times (on the amount of numbers you request):

$(document).ready(function(){
 var x = Math.floor(Math.random() * 10);
 var y = Math.floor(Math.random() * 10);
 var z = Math.floor(Math.random() * 10);
 var k = Math.floor(Math.random() * 10);
 var all = String(x) + String(y) + String(z) + String(k);
 $("body").append("<div class='alpha'> </div>");
 $(".alpha").text(all);
});

We did it * 10, so we don't get a (10) number (2 numbers instead of 1) and we removed the + 1 because we want to have 0's.

The script above will create a random 4 number password with 4 numbers between 1 to 0. You can add as many numbers as you want.

Stay tuned for more!

Fill out the form below to get started

find out what we can do for you 877 543 3110