javascript calculate random code example

Example 1: how to generate a random number in javascript

//To genereate a number between 0-1
Math.random();
//To generate a number that is a whole number rounded down
Math.floor(Math.random())
/*To generate a number that is a whole number rounded down between
1 and 10 */
Math.floor(Math.random() * 10) + 1 //the + 1 makes it so its not 0.

Example 2: js random

Math.floor(Math.random() * 10) + 1 // Random number Between 1 and 10
// First Math.random give us a random number between 0 and 0,99999
// The we multiply it by 10
// And we round dow with Math.floor
// We add 1 so the result will never be 0 

// Another Example:
h.floor(Math.random() * 20) + 10 // Random number Between 10 and 20

Tags:

Java Example