jQuery Random Number

A popular question on forums is how to create random numbers in jQuery. We don't really need to use jQuery for a simple task like this. The Math.random() method in JavaScript can be used to quickly create a random number between 0 and 1

But most of the time we need a whole number not a float,. In order to create a whole number, we can multiply the number generated by Math.random() by 10 and then round the number using the floor() method, like this:


This creates a number between 1 and 10 (for example 7.668625892) and then rounds it to the nearest number, in this case 8. If we wanted a random number between 0 and 7 we could multiply it by 7, like the following:

 Math.ceil(Math.random()*7); // 1,2,3,4,5,6 or 7

Have your say