Random numbers using Javascript

Nov 15, 2021

I developed this little random generator for a recent competition we held. We had a number of prizes and people could entry how many times they wanted. Each entry was added to an excel spreadsheet. We wanted to randomly select the winners from those listed in the spreadsheet. With the random generator, you enter the number of prizes on offer and then the number of entries (total number of rows in the spreadsheet) , click the Generate button and the unique winning numbers are displayed. (Could also be used to select random lotto numbers...) Cheers Gerry 

View

 

23 Replies
David Warmer

Here's an example of how to generate random numbers using JavaScript:

javascriptCopy code
// Generate a random integer between a minimum and maximum value function randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Generate a random floating-point number between a minimum and maximum value function randomFloat(min, max) { return Math.random() * (max - min) + min; } // Example usage console.log(randomInteger(1, 10)); // Generate a random integer between 1 and 10 console.log(randomFloat(1.0, 5.0)); // Generate a random floating-point number between 1.0 and 5.0

The randomInteger() function generates a random integer between a minimum and maximum value, inclusive of the minimum and maximum values. The randomFloat() function generates a random floating-point number between a minimum and maximum value, exclusive of the maximum value.

Note that the Math.random() function returns a random floating-point number between 0 and 1, but not including 1. By multiplying this value by the difference between the maximum and minimum values and adding the minimum value, we can generate a random number within the desired range.