Different ways to generate random numbers between two numbers in javascript
- Admin
- Sep 20, 2023
- Javascript
Learn multiple ways to generate random numbers between two numbers in javascript with examples.
For example, there are two numbers, min=1, and max=10. Random numbers between 1 and 10 are 1,2,3,4,5,6,7,8,9,10.
There are multiple ways we can generate random numbers.
Generate Random Numbers between two numbers with javascript?
Math.random() function generates a random floating number between 0 and 1. It returns possible values that are zero, less than 1, and exclude 1.
It returns a float number and used Math.floor() to round the lowest number.
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomNumber(1, 10));
It generates a random number between 1 and 10.
Similarly, The above function is simplified using ES6 arrow functions,
Here is an ES6 code to generate random numbers.
const getRandomNumber = (min, max) =>
Math.floor(Math.random() * (max - min + 1) + min);
console.log(getRandomNumber(1, 10));
Generate random numbers with underscore and lodash libraries
Underscore and lodash are javascript libraries, that provide utility functions.
If you used these libraries in your application, use the random(min, max) function
.
Here is a syntax
random(lower, upper, float - type);
lower
is a lower bound value and optional
upper
is the upper bound value
float-type
is true, returns a floating value
A random number is inclusive of lower and upper value
Returns a number between lower and upper value
_.random(1, 100); // returns integer number between 1 and 100
_.random(1, 1000); // returns integer number between 1 and 1000
_.random(10, true); // returns floating number between 1 and 10
Generate random numbers with a random npm library
In Nodejs, random is an npm library that provides advanced utility functions for generating random numbers. It returns boolean, integer, and floating random values. It uses normal and Poisson distribution using given parameters.
Here is a command to install to node application.
npm install --save random
Here is an ES5 javascript code to generate random numbers
const random = require("random");
random.int(1, 10); // 8
random.float(1, 10); // 6.3
use import with ES6 to create the random object.
import random from "random";
random.int(1, 10); // 8
random.float(1, 10); // 6.3
Conclusion
Learn multiple ways to return random numbers and float for given lower and upper values.