Greetings
This is another short and sweet posts, basically it involves using the Math. function to do some nifty tricks
Lets say that you want to get a random number between 1 and 10 and you dont know how. Well the answer is quite easy and it involves combining 2 Math. functions. Math.floor() and Math.random().
Math.random()
This function takes a random number between 0 and 1
Math.floor()
This function rounds a number down to it’s smaller number, for example. 4.4 would become 4, 4.6 would become 4 as well, -4.1 would become -5 as well as -4.6 would become -5 as well.
// random number between 0 and 1 //
$(document).ready(function(){
var x = Math.random();
$("body").append("<div class='alpha'> </div>");
$(".alpha").text(x);
});
// 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);
});
// 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);
});
Posted By: Dinulescu Alexandru Adrian
Last Edit: 14 Feb 2010 @ 11:37 PM
Email •
Permalink
Recent Comments