jQuery Random Number

random number

We don’t really need to use jQuery for a simple task like this. The Math.random() method in JavaScript can be used t create a random number between 0 and 1 (for example, .1682708465127408). 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:

Math.floor(Math.random()*10);

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, for example, 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

Photo by Mariano Kamp

Leave a Reply