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]
How to Add Options to a Select Box from a JS Object using jQuery
Use the jQuery $.each() Function You...How to set the width of a div element dynamically using jQuery
Use the JavaScript width() method You...Laravel 8 Create Custom Service Provider Example
In Laravel application, you have noticed...How to Implement Yajra Datatables in Laravel 8
Datatable is jQuery plugin that provides...How to compare two array values in PHP
Use the PHP array_diff() funct...