Javascript Generate a Random Number

  327 views   9 months ago Javascript

Sometimes while testing we often need to generate random numbers. Different language has its own functions to generate random numbers.

In web developing, we can do this from Javascript irrelavant to backend languages. In this article, we will also generate random numbers between specific range.

Math.random() function returns random float numbers between 0 and 1.

Math.random();
// 0.8213480830154087

We can get float numbers between specific range number by using it.

/**
 * returns a random float between min (inclusive) and max (exclusive)
 */
function getRandomNumbersBetweenRange(min, max) {
    return Math.random() * (max - min) + min;
}

Math.floor() function rounds off float number to integer. So if you want integer values, here you can get by the below function.

/**
 * returns a random integer between min (inclusive) and max (exclusive)
 */
function getRandomNumbersBetweenRange(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

However the above functions doesn't include the maximun number. If you also want to include the maximum number, then there is Math.ceil() function.

/**
 * returns a random integer between min (inclusive) and max (inclusive)
 */
function getRandomNumbersBetweenRange(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

These are basics way to generate numbers, you can also create your own functions and use.

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]