1. Introduction
In this article, we will present a method to generate random numbers from a specific range in JavaScript.
2. Get a random float number between min
and max
value
In general, to get a random number in JavaScript we will have to use Math.random()
a method that returns a floating-point, pseudo-random number in the range 0–1. The following example shows how to generate a random float number:
const randomFloat = (min, max) => Math.random() * (max - min) + min;
console.log(randomFloat(1, 100));
3. Get a random int value
Generating a random int number requires Math.floor()
method that will return the largest integer less than or equal to a given number. The following snippet generate random integer value between min
and max
range:
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(randomInt(1, 100));
4. Get a random boolean value
If we want to generate random boolean value (true/false) we can also use Math.random()
method and simply return true if the result is greaten or equal 0.5
. Check the following example:
const randomBool = () => Math.random() >= 0.5;
console.log(randomBool());
5. Conclusion
In this article, we present how to generate random float and int value using specified min
-max
range, and also a random boolean value. In all these cases we used JavaScript Math.random()
the method that generates a pseudo-random number.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}