Hi Friends 👋,
Welcome to Infinitbility ❤️!
Today, we are going to learn How to get a random number in typescript?, here we will use Math.ceil()
, Math.floor()
, and Math.random()
methods to generate random as per our requirement.
Before going to code, let first understand what is those methods.
-
Math.ceil()
The
Math.ceil()
function always rounds a number up to the next largest integer. -
Math.floor()
The
Math.floor()
function returns the largest integer less than or equal to a given number. -
Math.random()
The
Math.round()
function returns the value of a number rounded to the nearest integer.
Here, we will create a custom genrateRandomNumber()
method to generate numbers and it will expect min
and max
from ourselves.
/**
* Genrate random int
* @param min
* @param max
* @returns random int - min & max inclusive
*/
const genrateRandomNumber = (min: number, max: number) => {
min: number = Math.ceil(min);
max: number = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
genrateRandomNumber();
genrateRandomNumber(1000, 9000)
When you run the above code,
In the first console, you will get NaN
because it’s expected.
In the second console, you will get some 4-digit random numbers because I have mentioned 1000
to 9000
for generate number.
All the best 👍.