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.
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]
timedropper jQuery UI timepicker example
Sometimes, you may need to add time inpu...How to Install and Use Nano Text Editor in Linux
Many times, working in command line, man...How to create jQuery slide up and down toggle effect
Use the jQuery slideUp() and&n...How to Make a User an Administrator in Ubuntu
While your computer is shared with your...Laravel 8 auto logout a user after a time of inactivity
Sometimes we want to make automatic logg...